2013-06-05 26 views
1

我在工作中使用SQL Server,並且使用了OUTER APPLY子句可以幫助我不重複代碼。舉例來說,如果我有這樣的一個表:在其他RDBMS(不是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

+3

PostgreSQL 9.3將具有'LATERAL'這是SQL Server的'外部應用程序'的ANSI等效物 –

+0

謝謝,所以有ANSI等效物:) –

+1

一些示例在手冊中:http://www.postgresql.org /docs/9.3/static/queries-table-expressions.html#QUERIES-LATERAL –

回答

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 

甲骨文似乎使用LATERAL關鍵字internally雖然。

+0

標準'LATERAL'連接不一定是'CROSS JOIN'。在此處查看一些示例:http://www.postgresql.org/docs/9.3/static/queries-table-expressions.html#QUERIES-LATERAL –

+0

@a_horse_with_no_name此鏈接列出了橫向連接的三種用法:標準連接,交叉連接和外部交叉連接,所有這些都可以重寫爲具有相關結果集的笛卡爾積。 –

+0

你有沒有看到'...左加入橫向...'? –