0

我有一个表,其中包含如下数据,

Date            Custid  CreditDebit     Units   Value
2013-03-29 06:21:46.903     1       C   1   10
2013-03-29 06:21:46.903     1       C   2   11
2013-03-29 06:21:46.903     1       C   1   12
2013-03-29 06:21:46.903     1       C   2   13
2013-03-29 06:21:46.903     1       D   1   20
2013-03-29 06:21:46.903     1       D   2   21
2013-03-29 06:21:46.903     1       C   1   20
2013-03-29 06:21:46.903     1       C   2   21

我需要得到一个临时表输出如下,

Date            Custid  CreditDebit     Units   Value Balance
2013-03-29 06:21:46.903     1       C   1   42      42-20
2013-03-29 06:21:46.903     1       c   2   45      22+45-21
2013-03-29 06:21:46.903     1       D   1   20      ---
2013-03-29 06:21:46.903     1       D   2   21      ---

这是基于“CreditDebit”和单位的 Value 列的总和。我如何使用 CTE sql 查询来实现这一点

4

1 回答 1

2
;WITH summary_table_cte
     AS (SELECT Date,
                Custid,
                CreditDebit,
                Units,
                sum(value) AS [Value]
         FROM   YourTable
         GROUP  BY Date,
                   Custid,
                   CreditDebit,
                   Units)
SELECT *
FROM   summary_table_cte; 

注意语句开头的分号。CTE 之前的语句必须以分号结束。通过添加前缀WITH,您可以将其放在任何地方。

于 2013-03-29T09:06:24.313 回答