对于某些ID,从具有多行的表中选择具有标识符值的

时间:2013-10-07 23:31:09

标签: sql sql-server

我目前有以下结果:

ID    Location
1     NYC
1     LA
2     NYC
3     PIT

我想要以下内容:

ID    Location
1     Multiple
2     NYC
3     PIT

有谁知道一个简单的方法来实现这一目标?

3 个答案:

答案 0 :(得分:1)

使用casecountdistinct进行此处是一种方法:

select distinct id, 
  case when count(location) over (partition by id ) > 1 
    then 'Multiple' else location end Location
from yourtable

答案 1 :(得分:0)

使用sub-queryCOUNTCASEGROUP BY

SELECT mm.id, CASE WHEN mm.count > 1 THEN 'Multiple' ELSE loc END As Location
FROM
(SELECT COUNT(id) As count, id, MAX(location) As loc
FROM myTable
GROUP BY id) As mm;

SQL Fiddle

答案 2 :(得分:0)

select ID,case when MIN(name) = MAX(name) then  MIN(name) else 'multiple' end as Location
from <your tabel name>
group by id