翻转SQL结果

时间:2015-06-03 06:36:17

标签: sql sql-server-2008

如何在sql中执行此操作?

我有选择,结果是:

1 a
2 b
3 c
4 d
5 e

然后我希望结果显示为

1 2 3 4 5
a b c d e

谢谢大家!

3 个答案:

答案 0 :(得分:3)

您可以使用pivot

  Tuple<DateTime, decimal>

<强> SQL FIDDLE DEMO

答案 1 :(得分:1)

你可以使用PIVOT:

-- Create sample data

CREATE TABLE Test
(
  A INT,
  B NVARCHAR(10)
)
INSERT INTO Test (A, B) VALUES (1, 'a'), (2, 'b'), (3, 'c'), (4, 'd'), (5, 'e')

-- Pivot query

SELECT [1],[2],[3],[4],[5]
FROM
(
  SELECT A, B
  FROM Test
) x
PIVOT
(
  MIN(B)
  FOR A IN ([1],[2],[3],[4],[5])
) piv;

输出:

1   2   3   4   5
a   b   c   d   e

<强> SQL FIDDLE

正如您所问,动态支点应该是这样的:

SELECT @cols += ([Name]) + ','
FROM   (
        SELECT  Name
        FROM    Table
        ) a
SET @cols   = LEFT(@cols, LEN(@cols) - 1)
SET @sql    = 
'SELECT * 
 FROM 
    (
    SELECT Col1 as [NamePiv], 
           Col2 as [Val]
    FROM   Table1
    ) x
    PIVOT
    (
        MIN (Val)
        FOR NamePiv IN (' + @cols +') 
    ) p'

答案 2 :(得分:1)

您似乎需要使用pivot语句https://technet.microsoft.com/en-us/library/ms177410(v=sql.105).aspx

type | amount
abcd | 1234