SQL GROUP BY with LEFT JOIN MS SQL Server



我有一个日历表(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和每个month的一行,无论是否有视图。

对于上面的数据,我想要的结果是:
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

使用cross join生成行,然后使用left join导入数据:

select c.themonth, p.productid,
count(s.productid) as sales_in_month
from #calendar c cross join
(select distinct productid from stats) p left join
stats s
on s.productid = p.productid and
s.firstdayofmonth = c.themonth
group by c.themonth, p.productid;

最新更新