Summarise by week, even for empty rows

后端 未结 4 665
旧时难觅i
旧时难觅i 2021-01-21 23:14

I want to summarise the sum of sales.quantity by week, and to show the week number even if there are no sales.

I have setup a weeks table with 1-54 in there to use an ou

4条回答
  •  挽巷
    挽巷 (楼主)
    2021-01-21 23:37

    Try this:

    SELECT Weeks.WeekNum, SUM(sales.quantity) AS sales
    FROM Weeks 
    LEFT JOIN sales 
           ON Weeks.WeekNum = DATEPART(week, sales.transDate) and
              sales.transDate BETWEEN @fromDate AND @toDate
    WHERE Weeks.WeekNum BETWEEN DATEPART(week, @fromDate) AND 
                                DATEPART(week, @toDate)
    GROUP BY Weeks.WeekNum
    

提交回复
热议问题