如何在Sql中创建"月"列?

Bes*_*ska 6 sql-server

我有一组看起来像这样的数据(非常简化):

productId    Qty   dateOrdered
---------    ---   -----------
       1       2    10/10/2008
       1       1    11/10/2008
       1       2    10/10/2009
       2       3    10/12/2009
       1       1    10/15/2009
       2       2    11/15/2009
Run Code Online (Sandbox Code Playgroud)

除此之外,我们正在尝试创建一个查询来获取类似的内容:

productId  Year  Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec
---------  ----  --- --- --- --- --- --- --- --- --- --- --- ---
        1  2008    0   0   0   0   0   0   0   0   0   2   1   0
        1  2009    0   0   0   0   0   0   0   0   0   3   0   0
        2  2009    0   0   0   0   0   0   0   0   0   3   2   0
Run Code Online (Sandbox Code Playgroud)

我现在这样做的方式,我正在做12个选择,每个月一个,并把它们放在临时表中.然后我做了一个巨大的加入.一切正常,但这家伙是狗慢.

我知道这并不多,但我知道我几乎没有资格成为db世界中的一个tyro,我想知道是否有一个更好的高级方法,我可能会尝试.(我猜是有的.)

(我正在使用MS Sql Server,因此特定于该数据库的答案很好.)

(我刚开始看"PIVOT"作为一种可能的帮助,但我对此一无所知,所以如果有人想对此发表评论,那也可能有所帮助.)

Red*_*ter 10

select productId, Year(dateOrdered) Year
  ,isnull(sum(case when month(dateOrdered) = 1 then Qty end), 0) Jan
  ,isnull(sum(case when month(dateOrdered) = 2 then Qty end), 0) Feb 
  ,isnull(sum(case when month(dateOrdered) = 3 then Qty end), 0) Mar
  ,isnull(sum(case when month(dateOrdered) = 4 then Qty end), 0) Apr
  ,isnull(sum(case when month(dateOrdered) = 5 then Qty end), 0) May
  ,isnull(sum(case when month(dateOrdered) = 6 then Qty end), 0) Jun
  ,isnull(sum(case when month(dateOrdered) = 7 then Qty end), 0) Jul
  ,isnull(sum(case when month(dateOrdered) = 8 then Qty end), 0) Aug
  ,isnull(sum(case when month(dateOrdered) = 9 then Qty end), 0) Sep
  ,isnull(sum(case when month(dateOrdered) = 10 then Qty end), 0) Oct
  ,isnull(sum(case when month(dateOrdered) = 11 then Qty end), 0) Nov
  ,isnull(sum(case when month(dateOrdered) = 12 then Qty end), 0) Dec
from Table1
group by productId, Year(dateOrdered)
Run Code Online (Sandbox Code Playgroud)

SQL小提琴


Tur*_*key 0

您可以使用查询的联合而不是临时表,或者使用数据透视选项。

这是一个关于它的论坛讨论:

Sql Server 论坛 - 将按行数据显示为按列