繁体   English   中英

多行SQL选择查询

[英]Multi-row SQL Select Query

我需要一些SQL来为给定的用户返回任何行,其中存在多个行,但是它们都没有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

使用子查询取消用户的资格,使其具有primary_bran = 1的行。

select * from table t1
where not exists (select 1 from table
                  where user_id = t1.user_id
                  and primary_bran = 1)

如果只应返回至少包含两行的用户,则还要添加一个计数条件:

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

如果我理解正确,则想列出包含多个primary_bran <> 1记录的给定用户的所有行。

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM