2015-09-28 51 views
0

我有一個類似於下面的查詢。我想要的是如果IN語句中沒有特定值的記錄,則選擇null或空白。 有值由用戶輸入。檢查IN語句中每個值的存在性

select system_code, max(last_update_timestamp) as [last_update_timestamp] 
from table_name 
where system_code in ('E1','E2','E3') 
Group by system_code 

E1 has 100 records 
E2 has 20 records 
E3 has no records 

使用上面的查詢我得到這個結果:

Sytem_code  last_update_timestamp 
E1    '2014-09-28 11:35:10.647' 
E2    '2014-09-28 11:35:10.647' 

預計reuslt

Sytem_code  last_update_timestamp 
E1    '2014-09-28 11:35:10.647' 
E2    '2014-09-28 11:35:10.647' 
E3    Null or Blank 

任何幫助將不勝感激。

回答

3

使用Table Value Constructor建立包含IN運營商的所有值的在線表格。然後LEFT JOIN查詢到這個表:

SELECT x.sc, [last_update_timestamp] 
FROM (VALUES ('E1'), ('E2'), ('E3')) AS x(sc) 
LEFT JOIN (
    SELECT system_code, max(last_update_timestamp) as [last_update_timestamp] 
    FROM table_name 
    WHERE system_code IN ('E1','E2','E3') 
    GROUP BY system_code) AS t ON x.sc = t.system_code 

Demo here

+0

請注意,這隻適用於2008年和更新。 –

+0

@TimSchmelter是的,當然。如果他/她點擊我的答案中引用的msdn頁面上的*其他版本*,讀者可以很容易地推斷出這一點。 –

+2

因爲我已經提到過,所以不需要打開鏈接並點擊「其他版本」。我認爲這值得注意,因爲OP沒有提到他的版本。 (我仍然在2005年,所以這不適合我f.e.) –

1

該查詢適用於大多數數據庫引擎

select tmp.system_code, max(table_name.last_update_timestamp) as [last_update_timestamp] 
from 
(
    select 'E1' as system_code 
    union all 
    select 'E2' 
    union all 
    select 'E3' 
) tmp 
left join table_name on tmp.system_code = table_name.system_code 
        and table_name.system_code in ('E1','E2','E3') 
Group by tmp.system_code 
+0

我想和table_name.system_code( 'E1', 'E2', 'E3')是多餘的 – Paparazzi

+1

「適用於所有DB引擎「不,它不。也許是所有版本的SQL Server,但Oracle對所有選擇都需要一個from子句,並且在這種情況下有一個特殊的表DUAL。 –

1
SELECT x.sc, max(last_update_timestamp) as [last_update_timestamp] 
    FROM (VALUES ('E1'), ('E2'), ('E3')) AS x(sc) 
    LEFT JOIN table_name 
     ON table_name.system_code = x.sc 
GROUP BY x.sc