I need some SQL which returns any rows for a given user where multiple rows exist but none of them have primary_bran = 1
user_id dest_id bran primary_bran act action_pri
695 0 ZTZ 0 1 0
695 0 ZUA 0 1 0
695 0 ZUD 0 1 0
695 0 ZUS 0 1 0
695 0 ZUT 0 1 0
695 0 ZUV 0 1 0
695 0 ZVB 0 1 0
695 0 ZVC 0 1 0
695 0 ZVJ 0 1 0
695 0 ZVK 0 1 0
695 0 ZWU 0 1 0
695 0 ZWV 0 1 0
695 0 ZWX 0 1 0
695 0 ZXB 0 1 0
695 0 ZYK 0 1 0
695 0 ZYL 0 1 0
695 0 ZYN 0 1 0
Use the sub-query to disqualify users how has a row with primary_bran = 1.
select * from table t1
where not exists (select 1 from table
where user_id = t1.user_id
and primary_bran = 1)
If only users with at least 2 rows are supposed to be returned, also add a count condition:
select * from table t1
where not exists (select 1 from table
where user_id = t1.user_id
and primary_bran = 1)
and (select count(*) from table
where user_id = t1.user_id) >= 2
If I understand correctly, you want to list out all rows for given user who contains multiple primary_bran <> 1
records.
WITH WithRecordsCount AS
(
SELECT *, COUNT(user_id) OVER(PARTITION BY user_id) AS CNT
FROM yourtable
WHERE primary_bran <> 1 OR primary_bran IS NULL
)
SELECT * FROM WithRecordsCount WHERE CNT > 1
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.