虽然我想在我的问题上找到一个好的答案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
重点是将一些列转换为具有最可读和优雅代码的行。但我不希望将空列视为行。有没有什么办法可以在查询的WHERE子句中使用来自unfst的值?
答案 0 :(得分: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;