SQL语句求助

0
id   user_id  subject_id
1        1            11
2        1             12
3        1             13
4        2            11
5        2            12
6       2            15
7        3             13

1:  要subject_id  有11  和  12   但是没有13的useid
2:    要subject_id  有13   但是没有11和12  的useid
已邀请:
1

- 取是能力,舍是境界 2015-10-24 回答

以你现有的需求应该是能满足的。折腾好半天没有搞定。如果同一user_id下subject_id有重复就麻烦了。
with tmp as
(
select 1 id, 1 user_id , 11 subject_id
union all
select 2 , 1 , 12
union all
select 3 , 1 , 13
union all
select 4 , 2 , 11
union all
select 5 , 2 , 12
union all
select 6 , 2 , 15
union all
select 7 , 3 , 13
)
,tmp1 as
(
select user_id,
sum(case when subject_id in(11,12) then 1 when subject_id = 13 then -1 else 0 end) exists1,
sum(case when subject_id = 13 then 1 when subject_id in (11,12) then -1 else 0 end) exists2
from tmp
group by user_id
)
select user_id
from tmp1
where exists1 = 2 or exists2 = 1
1

老头子 - 专注是唯一的捷径 2015-10-23 回答

写where条件过滤不行吗?
where subject_id in (11,12) and subject_id <> 13

要回复问题请先登录注册