一个查询中的RowNumber()和SUM()

时间:2017-05-31 11:26:08

标签: sql sql-server tsql

有哪些方法可以使用rownumber()和一个字段的SUM(在这种情况下是钱)来获取最后一条记录? 我试图提出如下查询:

SELECT 
        [date]
        ,...
    FROM
        (
        SELECT
             CAST(t.timestamp AS DATE)              AS [date]
            ,.../some fields/
            ,row_number() over (partition by ca.logical_number order by t.timestamp DESC) as rownumber --last update(record) transaction
            --,amount_transferred = 
            --(
            --  SELECT
            --      ,SUM(t.money_value)     AS  amount_transferred
            --   FROM
            --      TO_Transaction t
            --  GROUP BY
            --      CAST(t.timestamp AS Date)
            --)

        ) AS t
    WHERE rownumber=1

查询应该做的是查找当前的钱包余额以及一天内转移的所有资金。 任何帮助都会受到重视。 感谢。

1 个答案:

答案 0 :(得分:4)

你也可以sum(field) over (...)

select
  row_number() over (partition by ca.logical_number order by t.timestamp DESC) as rownumber,
  sum(amount_transfered) over (partition by ca.logical_number ) as total_amount_transfered
from ...