2

需要根据日期和另一列计算表的总计。假设我有一张名为 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
4

2 回答 2

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

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

于 2010-12-01T15:16:48.997 回答
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

于 2010-12-01T15:21:20.387 回答