【问题标题】:Unpivot T-SQL query with manual column join使用手动列连接取消透视 T-SQL 查询
【发布时间】:2020-04-07 13:16:31
【问题描述】:

我正在尝试最小化代码行:

表:

Date1      Date2      Date3
12/03/2019 13/05/2019 01/03/2020
04/05/2018 17/06/2019 07/04/2020

....

从这里开始, 我正在使用如下所示的联合编写查询:

select 'Date1' as ColumnName,
       'This date is for something1' as ColumnMeaning
        max(Date1) as ColumnMax
from tableName
union
select 'Date2' as ColumnName,
       'This date is for something2' as ColumnMeaning
        max(Date2) as ColumnMax
from tableName
union
select 'Date3' as ColumnName,
       'This date is for something3' as ColumnMeaning
        max(Date3) as ColumnMax
from tableName

我想最小化这段代码,因为大约有 30 个日期列,这使得代码变得毫无意义地庞大。我试过 unpivot 运算符,但问题是,我无法复制 ColumnMeaning 柱子。

有什么方法可以有效地实现这一点吗?

【问题讨论】:

    标签: sql sql-server tsql pivot unpivot


    【解决方案1】:

    另一种选择是apply

    select dates, colname, colsomething, max(dates) as colmax
    from table t cross apply
         ( values (t.date1, 'date1', 'This date is for something1'),
                   . . .
                  (t.date30, 'date130', 'This date is for something30')
         ) tt(dates, colname, colsomething);
    group by colname, colsomething;
    

    【讨论】:

      【解决方案2】:

      嗯。 . .您似乎想要行中的数据而不是列中的数据。您可以在取消透视后使用聚合:

      select v.colname, v.colsomething, max(thedate)
      from table t cross apply
           ( values (t.date1, 'date1', 'This date is for something1'),
                     . . .
                    (t.date30, 'date130', 'This date is for something30')
           ) v(thedate, colname, colsomething)
      group by v.thedate, v.colsomething;
      

      如果性能是一个问题,在使用 cross apply 之前进行聚合会更有效。

      【讨论】:

        猜你喜欢
        • 2017-02-22
        • 2016-02-13
        • 1970-01-01
        • 1970-01-01
        • 2013-06-16
        • 2021-02-28
        • 2015-10-29
        • 2022-01-20
        • 1970-01-01
        相关资源
        最近更新 更多