多行SQL选择查询

时间:2015-02-02 08:57:09

标签: sql select

我需要一些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

2 个答案:

答案 0 :(得分:2)

使用子查询取消用户对primary_bran = 1的行的取消资格。

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

如果只应返回至少有2行的用户,还要添加计数条件:

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

答案 1 :(得分:0)

如果我理解正确,您希望列出包含多个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