T-SQL从行到列查看表

时间:2016-03-30 00:04:54

标签: sql-server tsql

我有一张如下表所示的表格:

Handler h = new Handler();
        h.postDelayed(new Runnable() {
            @Override
            public void run() {
                // TODO your code here
            }
        }, 2000L); 

我想创建一个显示如下的视图(按年份,奖金排序)

YEAR        QUARTER     BONUS
2013        Q1          1000       
2013        Q2          1500       
2013        Q3          1300      
2013        Q4          1500       
2014        Q1          2000       
2014        Q2          1300      
2014        Q3          1500       
2014        Q4          1300      
2015        Q1          1800       
2015        Q2          1300      
2015        Q3          1800       
2015        Q4          1800      

1 个答案:

答案 0 :(得分:0)

您可以使用ROW_NUMBER和条件聚合:

来实现
WITH Cte AS(
    SELECT *,
        rn = ROW_NUMBER() OVER(PARTITION BY [YEAR], BONUS ORDER BY QUARTER)
    FROM tbl
)
SELECT
    [YEAR],
    BONUS,
    QUARTER_1 = MAX(CASE WHEN rn = 1 THEN [QUARTER] END),
    QUARTER_2 = MAX(CASE WHEN rn = 2 THEN [QUARTER] END),
    QUARTER_3 = MAX(CASE WHEN rn = 3 THEN [QUARTER] END),
    QUARTER_4 = MAX(CASE WHEN rn = 4 THEN [QUARTER] END)
FROM Cte
GROUP BY [YEAR], BONUS
ORDER BY [YEAR], BONUS;

ONLINE DEMO