【问题标题】:SQL GROUP BY with LEFT JOIN MS SQL ServerSQL GROUP BY 与 LEFT JOIN MS SQL Server
【发布时间】: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


    【解决方案1】:

    使用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;
    

    【讨论】:

    • 我需要使用交叉连接吗?似乎与我的用例完全匹配的所有其他答案都没有使用交叉连接。
    • 如果我想获得相同产品和月份的单独总查询记录,我该如何将其添加到上面的代码中?也就是说,结果应该包括产品浏览总数和查询总数。
    • @user2470281 。 . .你能用适当的样本数据、期望的结果和清晰的解释提出一个新问题吗?
    猜你喜欢
    • 2016-04-11
    • 1970-01-01
    • 2013-03-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-08-31
    • 2010-09-29
    相关资源
    最近更新 更多