2014-10-17 33 views
0

表[現狀] 2005年樞軸具有以下數據:如何使用SQL Server基於查找表

ID Status 
1 PaymentPending 
2 Pending 
3 Paid 
4 Cancelled 
5 Error 

==================== ================

數據表具有以下結構:

ID WeekNumber StatusID 
1  1   1 
2  1   2 
3  1   3 
4  2   1 
5  2   2 
6  2   2 
7  2   3 

尋找一個樞軸

Week #  PaymentPending  Pending  Paid Cancelled 
Week 1   1    1   1   0 
Week 2   1    2   1   0 

回答

0

樞軸可能是這樣的:

SELECT * FROM 
    (SELECT 
     'Week ' + CAST(D.WeekNumber AS varchar(2)) [Week #], 
     S.Status 
    FROM DataTbl D 
    INNER JOIN Status S ON D.StatusID = S.ID 
    ) Derived 
PIVOT 
(
COUNT(Status) FOR Status IN 
    ([PaymentPending], [Pending], [Paid], [Cancelled]) -- add [Error] if needed 
) Pvt 

如果您期望在Status表項改變的數量,您可能要考慮使用一個生成列標題的動態數據透視表。事情是這樣的:

DECLARE @sql AS NVARCHAR(MAX) 
DECLARE @cols AS NVARCHAR(MAX) 

SELECT @cols = ISNULL(@cols + ',','') + QUOTENAME(Status) 
FROM (SELECT ID, Status FROM Status) AS Statuses ORDER BY ID 

SET @sql = 
    N'SELECT * FROM 
     (SELECT ''Week '' + CAST(D.WeekNumber AS varchar(2)) [Week #], S.Status 
    FROM Datatbl D 
    INNER JOIN Status S ON D.StatusID = S.ID) Q 
    PIVOT (
     COUNT(Status) 
      FOR Status IN (' + @cols + ') 
     ) AS Pvt' 

EXEC sp_executesql @sql; 

Sample SQL Fiddle

+0

而其他的解決方案也是有效的,該解決方案與動態SQL提供了我需要的最佳解決方案。謝謝 – DennisT 2014-10-21 12:15:53

0

可以使用基於CASE聚集與GROUP BY

SELECT 'Week ' + cast(WeekNumber as varchar(10)) as 'Week#', 
     SUM (CASE WHEN StatusId =1 THEN 1 else 0 end) as 'PaymentPending', 
     SUM (CASE WHEN StatusId =2 THEN 1 else 0 end) as 'Pending', 
     SUM (CASE WHEN StatusId =3 THEN 1 else 0 end) as 'Paid', 
     SUM (CASE WHEN StatusId =4 THEN 1 else 0 end) as 'Cancelled' 
FROM DataTbl D 
GROUP BY 'Week ' + cast(WeekNumber as varchar(10)) 
1
SELECT 'Week '+CAST(coun.WeekNumber AS VARCHAR(10)) [Week #],[PaymentPending],[Pending],[Paid],[Cancelled],[Error] FROM 
(SELECT [WeekNumber],[Status] FROM dbo.WeekDetails 
INNER JOIN [dbo].[Status] AS s 
ON [dbo].[WeekDetails].[StatusID] = [s].[ID]) AS wee 
PIVOT (COUNT(wee.[Status]) FOR wee.[Status] 
IN ([PaymentPending],[Pending],[Paid],[Cancelled],[Error])) AS Coun 
相關問題