SQL Server Sales of two different weeks without summing them in one single row

3duebb1j  于 12个月前  发布在  其他
关注(0)|答案(1)|浏览(85)

I am trying to get the sales of a week formatted by days of the week, the problem is that my query behaves like a normal Sum() , ignoring sales from different weeks of the same days. In the example database I am inserting two different sales on two different weeks and the same day of the week resulting in a single row of 38.92, instead of two rows with the sales according to that day of the week.

This is the query I'm using:

SELECT
    CASE WHEN weekdays = 1 THEN Total_Sales ELSE 0 END as Sunday,
    CASE WHEN weekdays = 2 THEN Total_Sales ELSE 0 END as Monday,
    CASE WHEN weekdays = 3 THEN Total_Sales ELSE 0 END as Tuesday,
    CASE WHEN weekdays = 4 THEN Total_Sales ELSE 0 END as Wednesday,
    CASE WHEN weekdays = 5 THEN Total_Sales ELSE 0 END as Thursday,
    CASE WHEN weekdays = 6 THEN Total_Sales ELSE 0 END as Friday,
    CASE WHEN weekdays = 7 THEN Total_Sales ELSE 0 END as Saturday
FROM
    (SELECT 
         DATEPART(WEEKDAY, date) AS Weekdays,
         SUM(sales) AS Total_Sales
     FROM Sales
     WHERE CAST(Date AS date) BETWEEN '2023-03-01' AND '2023-03-10'
     GROUP BY DATEPART(weekday, Date)) X

Current result:

SundayMondayTuesdayWednesdayThursdayFridaySaturday
30.000.000.000.000.000.000.00
0.006.000.000.000.000.000.00
0.000.000.000.000.0038.920.00
0.000.000.000.000.000.0040.55

Desired:

SundayMondayTuesdayWednesdayThursdayFridaySaturday
30.000.000.000.000.0013.840.00
0.006.000.000.000.0025.080.00
0.000.000.000.000.000.000.00
0.000.000.000.000.000.0040.55

Dbfiddle example: https://dbfiddle.uk/r-Qg8JDT

xpcnnkqh

xpcnnkqh1#

SELECT 
    CASE WHEN weekdays = 1 THEN total_quantity ELSE 0 END as Sunday,
    CASE WHEN weekdays = 2 THEN total_quantity ELSE 0 END as Monday,
    CASE WHEN weekdays = 3 THEN total_quantity ELSE 0 END as Tuesday,
    CASE WHEN weekdays = 4 THEN total_quantity ELSE 0 END as Wednesday,
    CASE WHEN weekdays = 5 THEN total_quantity ELSE 0 END as Thursday,
    CASE WHEN weekdays = 6 THEN total_quantity ELSE 0 END as Friday,
    CASE WHEN weekdays = 7 THEN total_quantity ELSE 0 END as Saturday
FROM(
 SELECT 
    datepart(WEEKDAY, date) as weekdays,
    SUM(sales) as total_quantity
FROM sales
where cast(date as date)between '2023-03-01' and '2023-03-30'
group by datepart(dayofyear, date), datepart(weekday,date))X

It seems to be ok for that friday.

Dbfiddle example: https://dbfiddle.uk/MbCfqFVY

相关问题