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

前端之家收集整理的这篇文章主要介绍了sql-server – 如何在Sql中创建“月”列?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我有一组看起来像这样的数据(非常简化):
  1. productId Qty dateOrdered
  2. --------- --- -----------
  3. 1 2 10/10/2008
  4. 1 1 11/10/2008
  5. 1 2 10/10/2009
  6. 2 3 10/12/2009
  7. 1 1 10/15/2009
  8. 2 2 11/15/2009

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

  1. productId Year Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec
  2. --------- ---- --- --- --- --- --- --- --- --- --- --- --- ---
  3. 1 2008 0 0 0 0 0 0 0 0 0 2 1 0
  4. 1 2009 0 0 0 0 0 0 0 0 0 3 0 0
  5. 2 2009 0 0 0 0 0 0 0 0 0 3 2 0

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

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

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

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

解决方法

  1. 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
  2. from Table1
  3. group by productId,Year(dateOrdered)

SQL Fiddle

猜你在找的MsSQL相关文章