SQL订单数据透视结果按月计算

时间:2013-03-09 15:38:55

标签: sql pivot unpivot

我需要根据月份或订单而不是按字母顺序排序行。

当我运行下面的查询时,我得到以下结果

Col Mon Tue Wed Thu Fri
--- --- --- --- --- ---
Feb 1   2   3   4   5
Jan 2   3   4   5   6 
Mar 3   4   5   6   7

我如何订购如下:

Col Mon Tue Wed Thu Fri
--- --- --- --- --- ---
Jan 2   3   4   5   6 
Feb 1   2   3   4   5
Mar 3   4   5   6   7

我的查询:

select *
from
(
  select LEFT(datename(dw,datetime),3) as DateWeek,
    col, 
    value
  from DataTable
  cross apply 
  (
    values ('Jan', JData), ('Feb', FData),  ('Mar', MData)
  ) c (col, value)
) src
pivot
(
  sum(value)
  for dateweek in (Mon, Tue, Wed, Thu, Fri)
) piv

目前我正在将值的行替换为:

values ('1.Jan', JData), ('2.Feb', FData),  ('3.Mar', MData)

我猜有更好的解决方案

2 个答案:

答案 0 :(得分:1)

试试这个:

select * from DataTable
order by convert(datetime, '2012/'+ Col +'/01') 

SQLFiddle

答案 1 :(得分:0)

感谢Wawrzyniec Sz。,我想出了解决方案。添加额外的列可以解决问题。

几个月的代码如下:

select col, Mon, Tue, Wed, Thu, Fri
from
(
  select LEFT(datename(dw,datetime),3) as DateWeek, 
    ord,
    col, 
    value
  from DataTable
  cross apply 
  (
    values ('1','Jan', AVol_Offered), ('2','Feb', OVol_Offered),  ('3','Mar', AAHT)
  ) c (ord, col, value)
) src
pivot
(
  sum(value)
  for dateweek in (Mon, Tue, Wed, Thu, Fri)
) piv
order by ord

这适用于其他值,例如,如果我想维护列为C,A,B(您不能将其命名为asc或des)的顺序,您也可以使用相同的代码,如下所示: / p>

select col, Mon, Tue, Wed, Thu, Fri
from
(
  select LEFT(datename(dw,datetime),3) as DateWeek, 
    ord,
    col, 
    value
  from DataTable
  cross apply 
  (
    values ('1','C', AVol_Offered), ('2','A', OVol_Offered),  ('3','B', AAHT)
  ) c (ord, col, value)
) src
pivot
(
  sum(value)
  for dateweek in (Mon, Tue, Wed, Thu, Fri)
) piv
order by ord

感谢您的帮助/提示