sql-server – 如何在Sql中创建“月”列?
发布时间:2020-05-24 00:11:38 所属栏目:MsSql 来源:互联网
导读:我有一组看起来像这样的数据(非常简化): productId Qty dateOrdered--------- --- ----------- 1 2 10/10/2008 1 1 11/10/2008 1 2 10/10/2009 2 3 10/1
|
我有一组看起来像这样的数据(非常简化): 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 (编辑:安卓应用网) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
