SQL使用CROSS JOIN运行总计

时间:2010-12-01 15:09:34

标签: sql join cross-join

需要根据日期和其他列运行总表。假设我有下表名为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

2 个答案:

答案 0 :(得分:2)

您是否只需要将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

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

答案 1 :(得分:0)

你走了。


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