2012-02-13 73 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進行分組時使用此值。