使用动态列旋转样本

时间:2015-06-10 15:31:02

标签: sql sql-server tsql pivot

我见过许多支点例子,但我没有发现任何适用于我的情况。我希望有人能帮助我。

我有这两个表

Entities Performance    
+----------+--------+----------+
| idEntiry | idWeek | idResult |
+----------+--------+----------+
| 1        | 1      | 1        |
| 2        | 1      | 1        |
| 3        | 1      | 2        |
| 1        | 2      | 3        |
| 2        | 2      | 1        |
| 3        | 2      | 2        |
| 1        | 3      | 3        |
| 2        | 3      | 1        |
| …        | …      | …        |
| 1        | 10     | 1        |
+----------+--------+----------+

周数是动态的 实体数量也是动态的

Performance details     
+----------+-------------+--------+
| idResult | Description | Color  |
+----------+-------------+--------+
|        1 | Bad         | Red    |
|        2 | Average     | Yellow |
|        3 | Good        | Green  |
+----------+-------------+--------+

这是所需的输出

           |               Weeks                |
+----------+---------+---------+------+---+-----+
| idEntity | 1       | 2       | 3    | … |  10 |
+----------+---------+---------+------+---+-----+
|        1 | Bad     | Good    | Good | … | Bad |
|        2 | Bad     | Bad     | Bad  | … |     |
|        3 | Average | Average |      | … |     |
+----------+---------+---------+------+---+-----+

谢谢!

1 个答案:

答案 0 :(得分:2)

这可能有助于您接近。

DECLARE @WeekStart INT,
        @WeekEnd INT

SELECT  @WeekStart = MIN(idWeek),
        @WeekEnd = MAX(idWeek)
FROM    dbo.WeeksTable

DECLARE @WeekColumns VARCHAR(MAX)

WHILE @WeekStart < @WeekEnd
BEGIN
    SET @WeekColumns = COALESCE(@WeekColumns + '],[', '[') + CONVERT(VARCHAR, @WeekStart)
    SET @WeekStart = @WeekStart + 1
END
SET @WeekColumns = CONCAT(@WeekColumns,'],[',CONVERT(VARCHAR, @WeekStart),']')

DECLARE @Sql VARCHAR(MAX) = '
SELECT idEntity, ' + @WeekColumns + ' FROM
(
SELECT  ep.idEntity,
        ep.idWeek,
        pd.Description
FROM    dbo.EntitiesPerformance ep
        JOIN dbo.PerformanceDetails pd on ep.idResult = pd.idResult
) src
PIVOT (
    MIN(Description)
    FOR idWeek IN (' + @WeekColumns + ')
) pvt
'
EXEC (@Sql)