我正在使用T-SQL
我有一个表:带有平台源的用户会话。
我需要获得仅使用“Android”和“桌面”的用户。
数据示例:
ID | Source | DateTime
1 | Android | 2016-06-01
1 | Desktop | 2016-06-01
2 | Android | 2016-06-02
3 | iOS | 2016-06-01
3 | Desktop | 2016-06-02
3 | Android | 2016-06-03
预期结果:
ID = 1
答案 0 :(得分:2)
我称之为set-within-sets查询。我喜欢使用group by
和having
来解决此问题,因为这是表达这些条件的非常灵活的方法:
select id
from t
group by id
having sum(case when source = 'Android' then 1 else 0 end) > 0 and -- has Android
sum(case when source = 'Desktop' then 1 else 0 end) > 0 and -- has Desktop
sum(case when source not in ('Android', 'Desktop') then 1 else 0 end) = 0 -- has nothing else
答案 1 :(得分:2)
试试这个:
SELECT Id
FROM mytable
GROUP BY Id
HAVING COUNT(*) = COUNT(CASE WHEN Source='Android' THEN 1 END) +
COUNT(CASE WHEN Source='Desktop' THEN 1 END) AND
COUNT(CASE WHEN Source='Desktop' THEN 1 END) > 0 AND
COUNT(CASE WHEN Source='Android' THEN 1 END) > 0
答案 2 :(得分:1)
试试这个
select id from your_table
group by id
having
max(case when source in ('Android') then 1 else 0 end))=1
and
max(case when source in ('Desktop') then 1 else 0 end))=1
and count(distinct source)=2
答案 3 :(得分:0)
尝试使用
Select *
from yourtable a
where a.source = 'Android'
and not exist (Select b.id
from yourtable b
where b.id = a.id and b.source <> 'Android')