2

虽然我试图在我的问题上找到很好的答案Analog of OUTER APPLY in other RDBMS (not SQL Server)我发现了相当不错的 PostgreSQL 解决方案:

create table Transactions
(
    ID int, Date timestamp, Amount decimal(29, 2), Amount2 decimal(29, 2)
);

insert into Transactions (ID, Date, Amount, Amount2)
select 1, current_timestamp, 100.00, null union all
select 2, current_timestamp, 25.00, 75.00;

select
    T.ID,
    T.Date,
    unnest(array[T.Amount, T.Amount2]) as Amount
from Transactions as T

SQL 小提琴

关键是用我能得到的最易读和最优雅的代码将一些列变成行。但我不想将空列视为行。有什么方法可以在查询的 WHERE 子句中使用 unnest 的值?

4

1 回答 1

2

您可以使用子查询并where过滤掉NULL值:

select id, date, Amount
from (select t.*, unnest(array[T.Amount, T.Amount2]) as Amount
      from Transactions as T
     ) t
where Amount is not null;

Postgres 不允许子句unnest中的方向。where

编辑:

Unnest使用数组的长度来确定行数。您可以使用标准 SQL 而不使用子查询来执行此操作,但您可能会发现它更混乱:

      select T.ID, T.Date,
             (case when n = 1 then T.Amount
                   when n = 2 then T.Amount2
              end) as Amount
      from Transactions T cross join
           (select 1 as n union all select 2) n
      where (case when n = 1 then T.Amount
                  when n = 2 then T.Amount2
             end) is not null;   
于 2013-07-27T11:37:01.840 回答