本月

2017-01-28 54 views
0

下面的查詢將返回以下結果本月

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); 
+0

什麼是'服務Date'的數據類型?你正在使用哪個版本的'Sql Server'? –

+0

類型是date – Ayman

+0

哪個版本的SQL SERVER? 2008,2012? –

回答

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] 
1

假設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);