检查IN语句

时间:2015-09-28 12:55:28

标签: sql-server tsql

我有一个如下查询。我想要的是如果IN语句中没有特定值的记录,则选择null或空白。 用户输入值。

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' 

预期重播

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 个答案:

答案 0 :(得分: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

答案 1 :(得分: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

答案 2 :(得分:1)

!