场景如下:第一要根据email分组,然后查询出他的status在1,2,3,4中的记录个数大于等于2的记录。(1,2,3,4为有效)
t_user   
  id email status
  1 [email protected] 1
  2 [email protected] 2
  3 [email protected] 3
  4 [email protected] 1
  5 [email protected] 2
  6 [email protected] 2
  7 [email protected] 3
  8 [email protected] 5
  9 [email protected] 5
 10 [email protected] 1
 11 [email protected] 1
 12 [email protected] 4
  如何写一个sql语句将t_user变成如下   
   id email status
  1 [email protected] 1
  2 [email protected] 2
  3 [email protected] 3
  4 [email protected] 1
  5 [email protected] 2
  6 [email protected] 2
  7 [email protected] 3
  11 [email protected] 1
 12 [email protected] 4

解决方案 »

  1.   

    with t as (
     select  1 id ,'[email protected]' email, 1 status from dual
     union all select  2 ,'[email protected]', 2 from dual
     union all select  3 ,'[email protected]', 3 from dual
     union all select  4 ,'[email protected]', 1 from dual
     union all select  5 ,'[email protected]', 2 from dual
     union all select  6 ,'[email protected]', 2 from dual
     union all select  7 ,'[email protected]', 3 from dual
     union all select  8 ,'[email protected]', 5 from dual
     union all select  9 ,'[email protected]', 5 from dual
     union all select 10 ,'[email protected]', 1 from dual
     union all select 11 ,'[email protected]', 1 from dual
     union all select 12 ,'[email protected]', 4 from dual
    )
    select  * from t where email  in (select email from t where status<=4 group by email having count(*)>=2 ) and status<=4
    order by id
      

  2.   

    我也不知道对不对。你试试,我这台机子没环境。select id,email,status,
    count(email) over(partition by emial order by status) count_email
    from tbl_test 
    where email in(
    select email from tbl_test where status<=4 group by email having count(*)>=2 )
    and status status <=4;
      

  3.   

    select id ,email ,status from(
    select id ,email ,status, sum(1)over(partition by email order by id ) rows_sum
    from t_user   
    where status<=4)
    where rows_sum>=2