获取当月产品的总数量

时间:2017-01-28 05:22:29

标签: sql sql-server

以下查询返回以下结果

Service Date  Product1 Product2 
01/Jun/2015    1           3
02/Jun/2015    2           5
01/Aug/2015    2           5
02/Aug/2015    2           5

而不是我希望每个月都能得到每个产品的总数量,所以输出应该是这样的。

Service Date  Product1 Product2 
Jun/2015       3           8
Aug/2015       4           10

查询

DECLARE @cols AS nvarchar(max),
        @query AS nvarchar(max)
SELECT
  @cols = STUFF((SELECT
    ',' + QUOTENAME(Product_Name)
  FROM dbo.Store INNER JOIN dbo.Servicelist ON dbo.Servicelist.Pro_ID = dbo.Store.Pro_ID 
  where CatID='2'
  GROUP BY Product_Name
  ORDER BY Product_Name
  FOR xml PATH (''), TYPE)
  .value('.', 'NVARCHAR(MAX)'), 1, 1, '')
SET @query = 'SELECT Replace(CONVERT(NVARCHAR, Service_Date, 126), '' '', ''/'') AS [Service Date],' + @cols + ' from ( select Service.Service_Date, Store.Product_Name, Servicelist.ProductQty FROM   dbo.Service INNER JOIN dbo.Servicelist ON dbo.Service.Service_ID = dbo.Servicelist.Service_ID INNER JOIN dbo.Store ON dbo.Servicelist.Pro_ID = dbo.Store.Pro_ID) x pivot ( SUM(ProductQty) for Product_Name in (' + @cols + ') ) p '
EXECUTE (@query);

2 个答案:

答案 0 :(得分:0)

假设Service_Date是日期类型,请尝试:

select
    convert(char(3), Service_Date, 100) +'/'+ CONVERT(CHAR(4), Service_Date, 120),
    sum(Product1),
    sum(Product2)
from t
group by convert(char(3), Service_Date, 100) +'/'+ CONVERT(CHAR(4), Service_Date, 120);

答案 1 :(得分:0)

改变您的透视查询

在数据透视表分组中,将日期更改为mmm/yyyy格式

SET @query ='SELECT Format(Service_Date,''MMM/yyyy'') AS [Service Date],'+ @cols+'
             FROM   (SELECT Service.Service_Date,
                           Store.Product_Name,
                           Servicelist.ProductQty
                    FROM   dbo.Service
                           INNER JOIN dbo.Servicelist
                                   ON dbo.Service.Service_ID = dbo.Servicelist.Service_ID
                           INNER JOIN dbo.Store
                                   ON dbo.Servicelist.Pro_ID = dbo.Store.Pro_ID) x
                   PIVOT ( Sum(ProductQty)
                         FOR Product_Name IN ('+ @cols +') ) p'

如果您使用的内容少于Sql Server 2012,请替换

Format(Service_Date,'MMM/yyyy') AS [Service Date]

使用

Replace(RIGHT(CONVERT(CHAR(11), Service_Date, 106), 8), ' ', '/') AS [Service Date]