需要检查where
案例,如果找不到where type='P'
则会记录type='C'
这是表格
paper_id | product_id | type
1 1 P
2 1 P
3 1 C
4 1 C
5 2 C
6 2 C
有product_id
1
和2
,需要获取具有type='P'
的记录,但那些记录没有type='P'
的产品会从记录中获取type='C'
查询后需要此结果
paper_id | product_id | type
1 1 P
2 1 P
5 2 C
6 2 C
我试试
select * from table where CASE WHEN type !='P' THEN type='C' ELSE type='P'END
但没有工作
答案 0 :(得分:0)
select paper_id, product_id, type from your_tab
where type = 'P'
union all
select t1.paper_id, t1.product_id, t1.type from your_tab t1
where t1.type = 'C'
and not exists (select 1 from your_tab t2
where t2.product_id = t1.product_id and t2.type = 'P');
答案 1 :(得分:0)
也许这会有所帮助
SELECT DISTINCT T.PRODUCT_ID, T.PAPER_ID, T.TYPE
FROM YOUR_TABLE T
WHERE (CASE
WHEN T.TYPE = 'P' THEN
'TRUE'
WHEN T.TYPE != 'P' THEN
(CASE
WHEN (SELECT COUNT(*)
FROM YOUR_TABLE T2
WHERE T2.PRODUCT_ID = T.PRODUCT_ID
AND T2.TYPE = 'P') = 0 THEN
'TRUE'
ELSE
'FALSE'
END)
END) = 'TRUE'