我有一个包含以下示例数据的表: -
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”开头的记录并忽略其他记录。
答案 0 :(得分:4)
试试这个:
SELECT ID, DESCRIPTION FROM Table
WHERE Description LIKE 'RETRO %'
OR ID IN (
SELECT ID FROM Table GROUP BY ID HAVING COUNT(*) = 1
)
答案 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
答案 2 :(得分: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
答案 3 :(得分:0)
这个答案可能最简单:
SELECT ID, Description
FROM (SELECT ID, Description
FROM TABLE
ORDER BY Description LIKE 'RETRO%' DESC, Description ASC) a
GROUP BY ID
这将对数据进行排序,以使Description
以RETRO
开头的行最高,以便在按ID
分组时使用此值。