在其他RDBMS(不是SQL Server)中使用OUTER APPLY的模拟

时间:2013-06-05 08:36:19

标签: mysql sql sql-server oracle postgresql

我正在使用SQL Server,我有一些很好的技巧和OUTER APPLY子句,这有助于我不重复代码。例如,如果我有这样的表:

create table Transactions
(
    ID bigint identity(1, 1) primary key, [Date] datetime, Amount decimal(29, 2), Amount2 decimal(29, 2)
)

insert into Transactions ([Date], Amount, Amount2)
select getdate(), 100.00, null union all
select getdate(), 25.00, 75.00

我想从中选择数据,例如我将为每个非空数量的行,我可以这样查询:

select
  T.ID,
  T.[Date],
  OA.Amount
from Transactions as T
  outer apply (
      select T.Amount as Amount union all
      select T.Amount2 as Amount
  ) as OA
where OA.Amount is not null

而不是使用union

select
  T.ID,
  T.[Date],
  T.Amount
from Transactions as T
where T.Amount is not null

union all

select
  T.ID,
  T.[Date],
  T.Amount2 as Amount
from Transactions as T
where T.Amount2 is not null

所以我想知道 - 其他RDBMS是否有这种可能性?

SQL FIDDLE

1 个答案:

答案 0 :(得分:1)

在Oracle中,横向连接是一个笛卡尔连接,其结果集取决于行的值。尚未引入新关键字(SQLFiddle):

SQL> CREATE OR REPLACE TYPE number_nt AS TABLE OF NUMBER;
  2  /

Type created
SQL> SELECT t.id, t.dt, u.column_value amount
  2    FROM Transactions t
  3   CROSS JOIN TABLE(number_nt(t.amount, t.amount2)) u;

        ID DT                AMOUNT
---------- ----------- ------------
         1 05/06/2013           100
         1 05/06/2013  
         2 05/06/2013            25
         2 05/06/2013            75

但Oracle似乎使用了LATERAL关键字internally