sql-server – 如何在Sql中创建“月”列?

我有一组看起来像这样的数据(非常简化):
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

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

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

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

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

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

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

解决方法

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)

SQL Fiddle

相关文章

SELECT a.*,b.dp_name,c.pa_name,fm_name=(CASE WHEN a.fm_n...
if not exists(select name from syscolumns where name=&am...
select a.*,pano=a.pa_no,b.pa_name,f.dp_name,e.fw_state_n...
要在 SQL Server 2019 中设置定时自动重启,可以使用 Window...
您收到的错误消息表明数据库 'EastRiver' 的...
首先我需要查询出需要使用SQL Server Profiler跟踪的数据库标...