Transpose Keep order

时间:2018-02-01 18:55:19

标签: sql sql-server

转置此信息enter image description here

我正在使用此查询

 SELECT MAX([WM Week]) [WM Week],WKDate,SUM(CAST(CAST([Value] AS DECIMAL(12, 5)) AS INT)) AS 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
GROUP BY unpvt.WKDate;

但是,我想保留顺序:sat qty,sun qty,mon qty等我正在以这种方式获取信息:

enter image description here

有任何想法将顺序保留在转置句中吗?

2 个答案:

答案 0 :(得分:2)

SELECT  MAX([WM Week]) [WM Week]
      , WKDate
      , SUM(CAST(CAST([Value] AS DECIMAL(12, 5)) AS INT)) AS [Value]
      , CASE WKDate WHEN 'Sat Qty' THEN 1
                    WHEN 'Sun Qty' THEN 2
                    WHEN 'Mon Qty' THEN 3
                    WHEN 'Tue Qty' THEN 4
                    WHEN 'Wed Qty' THEN 5
                    WHEN 'Thu Qty' THEN 6
                    WHEN 'Fri Qty' THEN 7
            END [OrderKey]
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
GROUP BY unpvt.WKDate
ORDER BY [OrderKey];

或者只是

SELECT  MAX([WM Week]) [WM Week]
      , WKDate
      , SUM(CAST(CAST([Value] AS DECIMAL(12, 5)) AS INT)) AS [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
GROUP BY unpvt.WKDate
ORDER BY CASE WKDate 
                    WHEN 'Sat Qty' THEN 1
                    WHEN 'Sun Qty' THEN 2
                    WHEN 'Mon Qty' THEN 3
                    WHEN 'Tue Qty' THEN 4
                    WHEN 'Wed Qty' THEN 5
                    WHEN 'Thu Qty' THEN 6
                    WHEN 'Fri Qty' THEN 7
            END;

答案 1 :(得分:0)

外部申请将允许您取消注册并添加订单栏。

select      MAX([WM Week]) [WM Week],
            WkDate,
            SUM(CAST(CAST([Value] AS DECIMAL(12, 5)) AS INT)) AS [Value],
from        s_Validation s
outer apply (
            values('Sat Qty', [Sat Qty], 1),
                  ('Sun Qty', [Sun Qty], 2),
                  ('Mon Qty', [Mon Qty], 3),
                  ('Tue Qty', [Tue Qty], 4),
                  ('Wed Qty', [Wed Qty], 5),
                  ('Thu Qty', [Thu Qty], 6),
                  ('Fri Qty', [Fri Qty], 7)
)           v(WkDate, [Value], [Order])
group by    WkDate, [Order]
order by    [Order]