SQL查询到行到列

时间:2016-05-27 14:41:45

标签: sql

我有一张这样的表

CREATE TABLE #CurrencyRate
(
     [Base] nvarchar(10), 
     [Quote] nvarchar(10), 
     [Amount] nvarchar(10)
) 

它有这样的数据

Base   Quote   Amount
---------------------
R1C1   R1C2    R1C3
R2C1   R2C2    R2C3

注意R1C1 =>第1行,第1列

我想输出

Row      Column    Attribute   Value
-----------------------------------------
1          1       Base        R1C1
1          2       Quote       R1C2
1          3       Amount      R1C3
2          1       Quote       R2C1
2          2       Amount      R2C2
2          3       Base        R2C3

是否可以通过一些SQL获得这样的输出?

提前致谢

2 个答案:

答案 0 :(得分:1)

Unpivot可能更简单,但您还需要以某种方式生成行号和列号...我使用窗口函数执行此操作但不确定表中行的顺序。

但如果你只处理3列,这也应该有用。

WITH cte as (
SELECT row_number() 
  over (partition by base,quote,amount order by base, quote Amount) as RN,
Base, Quote, Amount
FROM #CurrencyRate)

SELECT RN as Row, 1 as Column, 'Base', base as value FROM cte
UNION ALL
SELECT RN, 2, 'Quote', quote FROM cte
UNION ALL
SELECT RN, 3, 'Amount', Amount FROM cte

答案 1 :(得分:1)

select  
    Row,
    row_number() over (partition by row order by Row) Col,
    Value,
    Attribute
from (
    select Base, Quote, Amount,
    row_number() over (order by Base) Row
    from #CurrencyRate c
) a
unpivot
(
    Value for Attribute in ([Base], [Quote], [Amount])
) unpvt;