SQL SERVER PIVOT TABLE一行

时间:2015-04-23 02:05:55

标签: sql sql-server sql-server-2008

我有一张桌子,例如

  PAY    STAFF    AMOUNT       TAX
   1       40     10.00        1.5
   1       40     20.00        3.0
   1       40     15.00        2.0

我想要这样的输出表,例如

PAY  STAFF AMOUNT1 TAX1    AMOUNT2 TAX2   AMOUNT3    TAX3
 1    40     10    1.5       20   3.0      15.00     2.0

我如何得到这个?

1 个答案:

答案 0 :(得分:2)

您可以使用动态交叉表执行此操作。请阅读Jeff Moden的article作为参考:

SQL Fiddle

DECLARE @sql1 VARCHAR(4000) = ''
DECLARE @sql2 VARCHAR(4000) = ''
DECLARE @sql3 VARCHAR(4000) = ''

SELECT @sql1 =
'SELECT
      Pay
    , Staff
'
SELECT @sql2 = @sql2 +
'   , MAX(CASE WHEN RN = ' + CONVERT(VARCHAR(4), RN) + ' THEN Amount END) AS [Amount' + CONVERT(VARCHAR(4), RN) + ']' + CHAR(10) +
'   , MAX(CASE WHEN RN = ' + CONVERT(VARCHAR(4), RN) + ' THEN Tax END) AS [Tax' + CONVERT(VARCHAR(4), RN) + ']' + CHAR(10)
FROM(
    SELECT DISTINCT ROW_NUMBER() OVER(ORDER BY (SELECT NULL)) AS RN
    FROM YourTable
)t

SELECT @sql3 =
'FROM(
    SELECT *, RN=ROW_NUMBER() OVER(ORDER BY (SELECT NULL))
    FROM YourTable
)t
GROUP BY Pay, Staff
ORDER BY Pay, Staff'

PRINT (@sql1 + @sql2 + @sql3)
EXEC (@sql1 + @sql2 + @sql3)