2012-02-13 61 views
2

我有一个包含下面的示例数据表: -SQL SELECT DISTINCT ID其中说明含有一定的文本值

ID  Description 
1  John Doe 
2  Jane Doe 
3  RETRO John Doe 
3  John Doe 
4  Jane Doe 
4  RETRO Jane Doe 
5  Bobby 

ID列是不是因此主键副本ID的

我想从上表中选择所有记录,但是在复制ID的情况下,我只想选择以“RETRO”开头并忽略其他记录的记录。

回答

4

试试这个:

SELECT ID, DESCRIPTION FROM Table 
WHERE Description LIKE 'RETRO %' 
OR ID IN (
    SELECT ID FROM Table GROUP BY ID HAVING COUNT(*) = 1 
) 
1

你可以这样说:

select * from tablename where Description like 'RETRO%' and ID in (select ID from tablename group by ID having count(ID) > 1) 
UNION ALL 
select * from tablename where ID not in (select ID from tablename group by ID having count(ID) > 1) 
order by ID, Description 
0

没有UNION的选项:

select 
    id, 
    case 
     when (count(*) =1) then max(sd.name) 
     else (select sd2.name from sampleData sd2 where sd2.id=sd.id and name like 'Retro%') 
    end 

from sampledata SD 
group by id 
0

这个答案很可能是最简单的:

SELECT ID, Description 
FROM (SELECT ID, Description 
    FROM TABLE 
    ORDER BY Description LIKE 'RETRO%' DESC, Description ASC) a 
GROUP BY ID 

这将对数据进行排序,以便DescriptionRETRO开头的行数最高,以便在通过ID进行分组时使用此值。