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);
什麼是'服務Date'的數據類型?你正在使用哪個版本的'Sql Server'? –
類型是date – Ayman
哪個版本的SQL SERVER? 2008,2012? –