2015-09-28 53 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