【问题标题】:SQL query to rows to columns [duplicate]SQL查询到行到列[重复]
【发布时间】:2016-05-27 14:41:45
【问题描述】:

我有一张这样的桌子

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 得到这样的输出?

提前致谢

【问题讨论】:

  • 是的,它被称为 UNPIVOT,如果你用谷歌搜索这个词,你会发现很多例子。
  • 看起来像 SQL server 吗?如果是什么版本?什么决定了行的“顺序”?基数,报价然后金额还是什么?
  • 基准“R1C1”不是字面意义上的“R1C1”,是吗?

标签: sql


【解决方案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

【讨论】:

    【解决方案2】:
    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;
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-10-02
      • 2012-10-03
      • 1970-01-01
      相关资源
      最近更新 更多