【发布时间】:2021-11-06 03:50:40
【问题描述】:
我有一个日历表 (c),其中包含一组 3 个月的日期:
2021-06-01
2021-07-01
2021-08-01
我有一个统计表,其中包含网站上每个产品的视图。
Prod1 | 2021-06-01
Prod1 | 2021-06-01
Prod1 | 2021-08-01
Prod2 | 2021-07-01
Prod2 | 2021-08-01
Prod2 | 2021-08-01
我需要统计每个产品每月的浏览量,不管有没有浏览量。
我已关注 许多 SO 答案 (SQL - Group By with Left Join),但我看不出下面的代码有问题。
DECLARE @Start date
SET @Start=DATEADD(month, DATEDIFF(month, 0,DATEADD(month, -3, getdate())), 0)
SELECT
s.ProductID,
c.themonth,
ISNULL(Count(s.ProductID),0) As Total_Views
FROM
#calendar c
LEFT JOIN
(
SELECT ProductID,FirstDayOfMonth FROM Stats WHERE FirstDayofMonth >= @Start
) s
ON c.themonth = s.FirstDayOfMonth
GROUP BY
c.themonth,s.ProductID
ORDER BY s.ProductID,c.themonth
我只获得在特定月份有浏览量的 ProductID 的结果,而不是每个 ProductID 的一行以及每个月是否有浏览量。
有了上面的数据,我想要的结果是:
Prod1 | 2021-06-01 | 2
Prod1 | 2021-07-01 | 0
Prod1 | 2021-08-01 | 1
Prod2 | 2021-06-01 | 0
Prod2 | 2021-07-01 | 1
Prod2 | 2021-08-01 | 2
【问题讨论】:
标签: sql sql-server group-by left-join