SQL Group按星期几

时间:2017-10-31 15:44:21

标签: sql sql-server tsql

使用SQL Server 2012.我的视图有两个字段 - Machine Date和Total Mins。该视图仅显示上周的数据 - 这很好。然后我使用下面的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

然而,结果不是一行,它们随着每周的每一天而增加,即

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

但我需要将结果显示如下:

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

我哪里错了?

2 个答案:

答案 0 :(得分:1)

您想要聚合:

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;

答案 1 :(得分:1)

关于使用pviot的评论是另一种方法:

工作示例: http://data.stackexchange.com/stackoverflow/revision/749735/930554/pivot-data-by-day-of-week-from-date-field

我发现语法有点令人困惑,但这应该有效:

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;

datepart(dw,[MachineMidLineDate])部分返回1到7之间的数字,表示星期几,用于指定查询的[1],[2],[3]...部分中的列。

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