将行结果设置为SQL Server中的列

时间:2014-10-07 16:34:03

标签: sql sql-server

我需要将一些结果放在列中。见下面的例子......

SELECT *
FROM tblAccount
WHERE Code IN ('H20', 'T10')
ORDER BY ID, YearPaid

结果...

ID   YearPaid     Amount   Code   Name
-------------------------------------------
1    2011-01-01    31 50   H20    Service
1    2011-01-01    45 00   T10    Service
2    2011-01-02    31 50   H20    Benefit
2    2011-01-02    45 00   T10    Benefit
3    2011-01-03    31 20   H20    Pay
3    2011-01-03    45 00   T10    Pay

我需要将结果显示如下......

ID   YearPaid    Amount   Code   Name      Amount   Code
--------------------------------------------------------
1    2011-01-01   31 50   H20    Service    45 00   T10
2    2011-01-02   31 50   H20    Benefit    45 00   T10
3    2011-01-03   31 20   H20    Pay        45 00   T10 

我想过使用一个支点,但我没有聚合任何东西。

我可以为每个代码执行临时表,但它们必须是更好的方法。

任何帮助都会很棒!

1 个答案:

答案 0 :(得分:2)

我想过使用一个支点,但我没有聚合任何东西 ,这不一定是真的,很多时候当用户这么说时,你可以看到你可以使用minmax。因此,假设每个ID可以有2行,YearPaid:

;WITH CTE AS
(
    SELECT  *,
            RN = ROW_NUMBER() OVER(PARTITION BY ID, YearPaid ORDER BY ID) 
    FROM tblAccount
    WHERE Code IN ('H20', 'T10')
)
SELECT  ID, 
        YearPaid,
        MIN(CASE WHEN RN = 1 THEN Amount END) Amount1,
        MIN(CASE WHEN RN = 1 THEN Code END) Code1,
        MIN(CASE WHEN RN = 1 THEN Name END) Name1,
        MIN(CASE WHEN RN = 2 THEN Amount END) Amount2,
        MIN(CASE WHEN RN = 2 THEN Code END) Code2,
        MIN(CASE WHEN RN = 2 THEN Name END) Name2
FROM CTE
GROUP BY ID, 
         YearPaid