如何使用基于查找表的SQL Server 2005 Pivot

时间:2014-10-17 21:01:24

标签: sql sql-server sql-server-2005 pivot

table [Status]具有以下数据:

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

3 个答案:

答案 0 :(得分: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

答案 1 :(得分: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))

答案 2 :(得分: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