sql-server – 如何在Sql中创建“月”列?
发布时间:2020-12-12 07:45:38  所属栏目:MsSql教程  来源:网络整理 
            导读:我有一组看起来像这样的数据(非常简化): 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 除此之外,我们正在尝试创建一个查询来获取类似的内容: productI
                
                
                
            
                        我有一组看起来像这样的数据(非常简化): 
  
  
 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 (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!  | 
                  
推荐文章
            站长推荐
            - Sqlserver2008 2012配置文件流数据库FileStream
 - SQLServer2005 Pivot 转置使用动态列
 - sql-server – 在SQL Server中,如何为现有用户创
 - Sqlserver:sqlserver2005在安装过程中,提示“
 - 我可以在T-SQL SELECT中定义一个循环中的变量(像
 - sql-server – SQL Server 2008在Insert,Update之
 - 【Sqlserver】修改数据库表中的数据:对缺失的数
 - 仅在SQL Server上记录错误查询
 - SqlServer 之 sp_config 存储过程
 - sql-server – 为sql server中的一组行生成一个散
 
热点阅读
            