我有一个包含数据的表
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 ---
这是Value列的总和,它基于'CreditDebit'和Units。 如何使用CTE sql Query
实现此目的答案 0 :(得分: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
前加上它,你可以把它放在任何地方。