我需要比较来自按ID分组的不同客户的两个表的最终余额。这些表具有相同的ID但是一个具有多个ID条目而另一个没有。我需要从表中用多个条目对行进行求和,所以我只有一个最后的数字来进行计算。
表1:
ID, cost, traceNumber, TheDate
1, 200, 1001, 10/07/2011
1, -20, 1002, 10/08/2011
1, 130, 1003, 10/10/2011
2, 300, 1005, 10/10/2011
表2:
ID, cost
1, 200
2, 300
ID为1的结果,与200的表2相比为310,差值为110
查询将如下所示。
SELECT DISTINCT
Table1.ID,
Table1.TheDate ,
Table1.traceNumber,
Table1.[cost] AS Frost_Balance,
SUM(Table1.[cost]) AS SUM_Frost_Balance,
Table2.[cost] AS Ternean_Balance,
SUM(Table1.[cost]) - Table2.[cost] AS Ending_Balance,
FROM
Table1
INNER JOIN Table2 ON Table1.ID =Table2.CustomerID
GROUP BY
dbo.Frost.ID
查询必须在结果集中显示多个列,因为它将用于报告。我尝试按结果集中的所有列进行分组,但这给了我错误的结果。还有另一种计算需要总结的列的方法吗?
答案 0 :(得分:1)
您可以使用“Window Aggregate Function”,如下所示:
select
table1.*,
sum(table1.cost) over (partition by table1.id) sum_frost_balance,
table2.cost,
sum(table1.cost) over (partition by table1.id) - table2.cost ending_balance
from table1
join table2 on table1.id = table2.id
答案 1 :(得分:0)
这是你想要做的吗?
-- Data setup
CREATE TABLE [Table1]
(
[ID] INT,
[cost] INT,
[traceNumber] INT,
[TheDate] DATE
)
INSERT [Table1]
VALUES (1, 200, 1001, '10/07/2011'),
(1, -20, 1002, '10/08/2011'),
(1, 130, 1003, '10/10/2011'),
(2, 300, 1005, '10/10/2011')
CREATE TABLE [Table2]
(
[ID] INT,
[cost] INT
)
INSERT [Table2]
VALUES (1, 200),
(2, 300)
-- Query
;WITH [cteTable1Sum] AS
(
SELECT [ID], SUM([cost]) AS [cost]
FROM [Table1]
GROUP BY [ID]
)
SELECT [Table1].[ID],
[Table1].[TheDate],
[Table1].[traceNumber],
[Table1].[cost] AS [Frost_Balance],
cte.[cost] AS [SUM_Frost_Balance],
[Table2].[cost] AS [Ternean_Balance],
cte.[cost] - [Table2].[cost] AS [Ending_Balance]
FROM [Table1]
INNER JOIN [Table2]
ON [Table1].[ID] = [Table2].[ID]
INNER JOIN [cteTable1Sum] cte
ON [Table1].[ID] = cte.[ID]