2012-07-25 96 views
2

是否可以在另一個SQL查詢上運行SQL查詢? 我有一個SQL查詢,使用Union All子句將許多列編譯成一個列。我需要使用小組條款,但你會發現這是不可能的。有沒有辦法在這個上運行另一個SQL查詢?SQL - 在SQL查詢上執行SQL查詢

查詢:

Select Ins1 as Insurance 

From InsAuth2 
WHERE Ins1 IS NOT NULL 
Group By Ins1 
Union All 
Select Ins2 as Insurance 
From InsAuth2 
WHERE Ins2 IS NOT NULL 
Group By Ins2 
Union All 
Select Ins3 as Insurance 
From InsAuth2 
WHERE Ins3 IS NOT NULL 
Union All 
Select Ins4 as Insurance 
From InsAuth2 
WHERE Ins4 IS NOT NULL 
Union All 
Select Ins5 as Insurance 
From InsAuth2 
WHERE Ins5 IS NOT NULL 

我需要能夠從這個編譯列選擇唯一值。我可以在每個語句中使用一個組,但是這隻會返回原始列中的唯一值。如果一列的唯一值對另一列唯一,則編譯列可能不具有所有唯一值。因此,我必須有另一個SQL查詢在這一個上運行。有什麼建議麼?

+1

是的,你可以。只需在適當的列上執行一個外部查詢與羣組 – nawfal 2012-07-25 14:54:49

回答

5

使用的內部查詢即

SELECT * 
FROM 
(
    YourQueryHere 
) Inn 
GROUP BY YourColumnHere 
+0

非常感謝你! – eatonphil 2012-07-25 15:01:49

3

使用派生表和獨特的:

select distinct Insurance 
from 
(
    Select Ins1 as Insurance 
    From InsAuth2 
    WHERE Ins1 IS NOT NULL 
    Union All 
    Select Ins2 as Insurance 
    From InsAuth2 
    WHERE Ins2 IS NOT NULL 
    ... 
) table_alias 
+0

非常感謝你! – eatonphil 2012-07-25 15:00:52

+0

@phileaton不客氣:-) – 2012-07-25 15:01:31

3

如果您使用的UNION代替UNION ALL它會過濾掉重複

Select Ins1 as Insurance 
From InsAuth2 
WHERE Ins1 IS NOT NULL 
Group By Ins1 
Union 
Select Ins2 as Insurance 
From InsAuth2 
WHERE Ins2 IS NOT NULL 
Group By Ins2 
Union 
Select Ins3 as Insurance 
From InsAuth2 
WHERE Ins3 IS NOT NULL 
Union 
Select Ins4 as Insurance 
From InsAuth2 
WHERE Ins4 IS NOT NULL 
Union 
Select Ins5 as Insurance 
From InsAuth2 
WHERE Ins5 IS NOT NULL 
+0

+1,這是如此真實和簡單。 – 2012-07-25 15:02:31

0

嘗試使用UNION而不是UNION ALL

謝謝

+0

應該是一個評論。 – 2016-08-10 09:14:37

+0

嘗試以下操作: – Jahirul 2016-08-30 08:48:35

+0

嘗試以下操作:選擇INS1保險從InsAuth2 WHERE INS1 IS NOT NULL 聯盟 選擇INS2保險從InsAuth2 WHERE INS2 IS NOT NULL 聯盟 選擇INS3保險從InsAuth2 WHERE INS3 IS NOT NULL Union 從InsAuth2中選擇Ins4作爲保險WHERE Ins4 IS NOT NULL Union 從InsAuth2中選擇Ins5作爲保險WHERE Ins5 IS NOT NULL – Jahirul 2016-08-30 08:49:10