使用 CROSS JOIN 的 SQL 运行总计

发布于 2024-10-05 09:10:56 字数 788 浏览 4 评论 0原文

需要根据日期和另一列对表进行总计。假设我有一个名为 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

任谁 2024-10-12 09:10:56

您不需要将 Client 添加到 JOIN 中吗?

SELECT a.Day, a.Client, SUM(1) AS RunningTotal
FROM Sales a 
JOIN Sales b ON b.Day <= a.Day and a.Client = b.Client 
GROUP BY a.Day, a.Client
ORDER BY a.Day

顺便说一句:这种计算运行总计的方法仅真正适合小型输入集。所需的工作呈指数级增长。

Don't you just need to add Client into the JOIN?

SELECT a.Day, a.Client, SUM(1) AS RunningTotal
FROM Sales a 
JOIN Sales b ON b.Day <= a.Day and a.Client = b.Client 
GROUP BY a.Day, a.Client
ORDER BY a.Day

BTW: This approach to calculating running totals is only really suitable for small input sets. The work required grows exponentially.

野稚 2024-10-12 09:10:56

干得好。


Select a.Day, a.Client, SUM(1) AS RunningTotal
From dbo.Sales a, dbo.Sales b
Where b.Day <= a.Day And a.Client = b.Client
Group By a.Day, a.Client
Order By a.Day

Here you go.


Select a.Day, a.Client, SUM(1) AS RunningTotal
From dbo.Sales a, dbo.Sales b
Where b.Day <= a.Day And a.Client = b.Client
Group By a.Day, a.Client
Order By a.Day

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文