【问题标题】:Row column operation in SQL Server [closed]SQL Server中的行列操作[关闭]
【发布时间】:2021-07-18 09:56:59
【问题描述】:

我有一张这样的桌子:

我想从这个表中得到如下结果。我如何在 SQL Server 中做到这一点?

使用大小写时的输出

【问题讨论】:

    标签: sql sql-server tsql


    【解决方案1】:

    您可以使用条件聚合:

    select max(case when col1 = 'a' then e end) as a_e,
           max(case when col1 = 'a' then f end) as a_f,
           max(case when col1 = 'a' then g end) as a_g,
           max(case when col1 = 'b' then e end) as b_e,
           max(case when col1 = 'b' then f end) as b_f,
           max(case when col1 = 'b' then g end) as b_g,
           max(case when col1 = 'c' then e end) as c_e,
           max(case when col1 = 'c' then f end) as c_f,
           max(case when col1 = 'c' then g end) as c_g,
           max(case when col1 = 'd' then e end) as d_e,
           max(case when col1 = 'd' then f end) as d_f,
           max(case when col1 = 'd' then g end) as d_g
    from t;
    

    【讨论】:

    • 感谢您的回答。我以前试过这个,但它没有给出我想要的确切结果。将不匹配的记录返回为 NULL。
    • 我将输出添加到问题中。如您所见,使用 Case When 时返回 NULL 值。
    • @uckocaman 。 . .除非使用聚合函数,否则条件 聚合 不是聚合。我确定了答案。
    • 感谢您的关注和回复。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-01-24
    • 2022-06-13
    • 2018-12-29
    • 1970-01-01
    • 2023-03-07
    • 2017-11-02
    • 2018-05-15
    相关资源
    最近更新 更多