使用手动列连接的 Unpivot T-SQL 查询

Unpivot T-SQL query with manual column join

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

Table:

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 柱子。

有什么方法可以有效实现吗?

另一种选择是 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;

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

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 之前进行聚合会更有效。