简体   繁体   中英

SQL Group by Day of Week

Using SQL Server 2012. I have a view that has two fields - Machine Date and Total Mins. The view is only showing data from the previous week - this works fine. I then have another view based on this view using the below SQL:

SELECT        
    CASE WHEN DATENAME(dw, MachineMidLineDate) = 'Sunday' THEN [Total Mins] END AS Sun, 
    CASE WHEN DATENAME(dw, MachineMidLineDate) = 'Monday' THEN [Total Mins] END AS Mon, 
    CASE WHEN DATENAME(dw, MachineMidLineDate) = 'Tuesday' THEN [Total Mins] END AS Tues, 
    CASE WHEN DATENAME(dw, MachineMidLineDate) = 'Wednesday' THEN [Total Mins] END AS Wed, 
    CASE WHEN DATENAME(dw, MachineMidLineDate) = 'Thursday' THEN [Total Mins] END AS Thursday, 
    CASE WHEN DATENAME(dw, MachineMidLineDate) = 'Friday' THEN [Total Mins] END AS Friday, 
    CASE WHEN DATENAME(dw, MachineMidLineDate) = 'Saturday' THEN [Total Mins] END AS Sat
FROM
    dbo.vw_Machine_Minutes_Overview

However, the results are not on one line, they increase with each day of the week ie

Sun    Mon   Tues   Wed  Thurs  Fri   Sat
10     
       15
              25
                    20
                          21
                                12

But I need the results to show like this:

Sun    Mon   Tues   Wed  Thurs  Fri   Sat
10     15     25    20    21    12

Where am I going wrong?

You want aggregation:

SELECT SUM(CASE WHEN DATENAME(dw, MachineMidLineDate) = 'Sunday' THEN [Total Mins] END) AS Sun,
       SUM(CASE WHEN DATENAME(dw, MachineMidLineDate) = 'Monday' THEN [Total Mins] END) AS Mon,
      . . . 
FROM dbo.vw_Machine_Minutes_Overview;

The comment about using pviot is another way to do it:

Working example: http://data.stackexchange.com/stackoverflow/revision/749735/930554/pivot-data-by-day-of-week-from-date-field

I find the syntax a bit confusing but this should work:

select *
from 
(
select  datepart(dw,[MachineMidLineDate]) as DayOfWeek, [Total Mins]
  from #vw_Machine_Minutes_Overview 
) src
pivot
(
  sum([Total Mins])
  for DayOfWeek in ([1], [2], [3],[4],[5],[6],[7])
) piv;

The datepart(dw,[MachineMidLineDate]) part returns a number between 1 and 7 representing the day of the week, that is used to specify the columns in the [1],[2],[3]... part of the query.

datepart: https://docs.microsoft.com/en-us/sql/t-sql/functions/datepart-transact-sql

pivot: https://technet.microsoft.com/en-us/library/ms177410(v=sql.105).aspx

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM