我正在使用此查询:
SELECT
DISTINCT(MAX([WM Week])) WKDate
,SUM(CAST(CAST([Sat Qty] AS DECIMAL(12, 5)) AS INT)) [Sat Qty]
,SUM(CAST(CAST([Sun Qty] AS DECIMAL(12, 5)) AS INT)) [Sun Qty]
,SUM(CAST(CAST([Mon Qty] AS DECIMAL(12, 5)) AS INT)) [Mon Qty]
,SUM(CAST(CAST([Tue Qty] AS DECIMAL(12, 5)) AS INT)) [Tue Qty]
,SUM(CAST(CAST([Wed Qty] AS DECIMAL(12, 5)) AS INT)) [Wed Qty]
,SUM(CAST(CAST([Thu Qty] AS DECIMAL(12, 5)) AS INT)) [Thu Qty]
,SUM(CAST(CAST([Fri Qty] AS DECIMAL(12, 5)) AS INT)) [Fri Qty]
FROM
[dbo].[s_Validation]
获取此信息:
但我需要得到这样的东西:
WKDate | Dayname | Value
--------------+----------+--------
201749.00000 | Sat Qty | 8978
201749.00000 | Sun Qty | 5251
201749.00000 | Mon Qty | 0
201749.00000 | Tue Qty | 2653
201749.00000 | Wed Qty | 2186
201749.00000 | Thu Qty | 2201
201749.00000 | Fri Qty | 2232
我正在使用以下查询,但我不知道很难对枢轴句中的数据求和
SELECT
[WM Week], WKDate, Value
FROM
[dbo].[s_Validation]
UNPIVOT
(Value FOR WKDate IN
([Sat Qty], [Sun Qty], [Mon Qty], [Tue Qty], [Wed Qty], [Thu Qty], [Fri Qty])
)AS unpvt;
答案 0 :(得分:1)
我倾向于使用APPLY
进行解体。其余的只是简单的聚合:
SELECT w.[WM Week], v.which, SUM(v.value)
FROM dbo.s_SellThru_WMT_Validation w OUTER APPLY
(VALUES ('Sat', [Sat Qty]),
('Sun', [Sun Qty]),
('Mon', [Mon Qty]),
('Tue', [Tue Qty]),
('Wed', [Wed Qty]),
('Thu', [Thu Qty]),
('Fri', [Fri Qty])
) v(which, amt)
GROUP BY [WM Week], v.which;