使用 CROSS JOIN 的 SQL 运行总计
需要根据日期和另一列对表进行总计。假设我有一个名为 Sales 的表:
Day Client
1 Smith, J
3 Johnson, B
6 Fuller, A
7 Smith, J
8 Johnson, B
9 Lee, M
我运行以下查询:
SELECT a.Day, a.Client, SUM(1) AS RunningTotal
FROM Sales a CROSS JOIN Sales b
WHERE (b.Day <= a.Day)
GROUP BY a.Day, a.Client
ORDER BY a.Day
这给出了以下结果:
Day Client RunningTotal
1 Smith, J 1
3 Johnson, B 2
6 Fuller, A 3
7 Smith, J 4
8 Johnson, B 5
9 Lee, M 6
但这只正确了一半。我希望运行总计基于当天和客户。我想要的表如下所示:
Day Client RunningTotal
1 Smith, J 1
3 Johnson, B 1
6 Fuller, A 1
7 Smith, J 2
8 Johnson, B 2
9 Lee, M 1
Need running total of a table based on date and another column. Say I have the following table called Sales:
Day Client
1 Smith, J
3 Johnson, B
6 Fuller, A
7 Smith, J
8 Johnson, B
9 Lee, M
I run the following query:
SELECT a.Day, a.Client, SUM(1) AS RunningTotal
FROM Sales a CROSS JOIN Sales b
WHERE (b.Day <= a.Day)
GROUP BY a.Day, a.Client
ORDER BY a.Day
This gives me the following:
Day Client RunningTotal
1 Smith, J 1
3 Johnson, B 2
6 Fuller, A 3
7 Smith, J 4
8 Johnson, B 5
9 Lee, M 6
But this is only half correct. I want the running total to be based on the day AND client. The table I want looks like this:
Day Client RunningTotal
1 Smith, J 1
3 Johnson, B 1
6 Fuller, A 1
7 Smith, J 2
8 Johnson, B 2
9 Lee, M 1
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您不需要将
Client
添加到 JOIN 中吗?顺便说一句:这种计算运行总计的方法仅真正适合小型输入集。所需的工作呈指数级增长。
Don't you just need to add
Client
into the JOIN?BTW: This approach to calculating running totals is only really suitable for small input sets. The work required grows exponentially.
干得好。
Here you go.