将行旋转到列

时间:2016-05-26 12:12:13

标签: sql sql-server

如何实现以下? 任何人帮助我

col_1 col_2
A     1
B     1
C     1
B     2
C     4
A     2
A     6

输出:

A B C
1 1 1
2 2 4
6

2 个答案:

答案 0 :(得分:1)

这将完成这项工作,但想要这样做似乎很奇怪,所以我可能错过了什么?

CREATE TABLE #table (col1 CHAR(1), col2 INT);
INSERT INTO #table SELECT 'A', 1;
INSERT INTO #table SELECT 'B', 1;
INSERT INTO #table SELECT 'C', 1;
INSERT INTO #table SELECT 'B', 2;
INSERT INTO #table SELECT 'C', 4;
INSERT INTO #table SELECT 'A', 2;
INSERT INTO #table SELECT 'A', 6;

WITH Ranked AS (
    SELECT
        *,
        ROW_NUMBER() OVER (PARTITION BY col1 ORDER BY col2) AS rank_id
    FROM
        #table),
Numbers AS (
    SELECT 1 AS number
    UNION ALL
    SELECT number + 1 FROM Numbers WHERE number < 50)
SELECT
    MAX(CASE WHEN col1 = 'A' THEN col2 END) AS [A],
    MAX(CASE WHEN col1 = 'B' THEN col2 END) AS [B],
    MAX(CASE WHEN col1 = 'C' THEN col2 END) AS [C]
FROM
    Numbers n
    INNER JOIN Ranked r ON r.rank_id = n.number
GROUP BY
    n.number;

结果是:

A   B   C
1   1   1
2   2   4
6   NULL    NULL

答案 1 :(得分:1)

看起来你试图在没有聚合的情况下进行转动?这是另一种选择:

select A, B, C from 
( select col1, col2, dense_rank() over (partition by col1 order by col2) dr from #table) t
pivot
( max(t.col2) for t.col1 in (A, B, C)) pvt;

另外,请查看更多示例/讨论:TSQL Pivot without aggregate function