在视图的结果集中返回具有非聚合列的聚合列的最佳方法是什么
我需要比较按 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 的结果为 310,与表 2 的 200 相比,相差 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
查询必须在结果集中显示多个列,因为它将是用于报告。我尝试按结果集中的所有列进行分组,但这给了我错误的结果。还有另一种方法来计算需要求和的列吗?
I need to compare the final balances of two tables from different clients grouped by ID. The tables have the same ID's But one has multiple ID entries and the other does not. I need to sum row from the table with multiple entries so I have just one final number to do calculations with.
Table1:
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
Table2:
ID, cost
1, 200
2, 300
Result for ID 1, would be 310 compared to table2 of 200 with a difference of 110
The Query will look something like this.
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
The query has to display multiple columns in the result set because it is going to be used to report on. I tried grouping by all columns in the result set but that gave me wrong results. Is there another way to compute the column that needs to be summed up?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可以使用“窗口聚合函数”,如下所示:
You can use a "Window Aggregate Function" like this:
这就是你想做的吗?
Is this what you're trying to do?