根据条件选择单行

toiithl6  于 2021-07-26  发布在  Java
关注(0)|答案(2)|浏览(229)

我有一些麻烦,检索只有一行的情况下,重复或基于某些条件。
假设我有一张这样的table:
数据:

+-----+---------+------------+
| id: | caseId: |  userId:   |
+-----+---------+------------+
| a   |  3      |   sd87     |
| a   | <null>  |   sd87     |
| a   | <null>  |   sd87     |
| a   |  5      |   cz6      |
| b   | <null>  |    87      |
| b   | <null>  |    87      |
| b   | <null>  |    87      |
| d   |  22     |   ah54     |
| d   | <null>  |   ah54     |
| d   | <null>  |   fr45     |
| d   |  21     |   ah54     |
+-----+---------+------------+

我需要提取的是:
结果:

+-----+---------+------------+
| id: | caseId: |  userId:   |
+-----+---------+------------+
| a   |  3      |   sd87     |
| a   |  5      |    cz6     |
| b   | <null>  |    87      |
| d   |  22     |   ah54     |
| d   | <null>  |   fr45     |
| d   |  21     |   ah54     |
+-----+---------+------------+

我试过这样问

select id,caseId,UserId
from datas
group by id,caseId,UserId

但并不是所有的场景都适用。
我应该如何更改查询?
提前谢谢!
编辑:我希望保留哪一行的解释。
对于相同的id,我首先考虑与caseid关联的userid。如果caseid为null,则保留caseid为null的行。
如果一个userid有一个caseid行和一个或多个caseid为null的行,我将保持caseid为notnull的行。
如果一个userid有两行或多行caseid不为null并且它们之间不同,我需要保留所有行。当然,如果我也有空行,我不会考虑它们。
希望现在更明朗了。
编辑2:
感谢@gordonlinoff的解决方案,不幸的是,它不能与我的数据集一起工作

select distinct d.*
from datas d
where d.caseId is not null or
      not exists (select 1
                  from datas d2 
                  where d2.userid = d.userid and d2.caseid is not null
                 );

我在not exists子查询中添加了一个比较d2.id和d.id的密码

select distinct d.*
from datas d
where d.caseId is not null or
      not exists (select 1
                  from datas d2 
                  where d2.id = d.id and d2.userid = d.userid and d2.caseid is not null
                 );

现在我得到了我所需要的。
谢谢大家!

oewdyzsn

oewdyzsn1#

这不是真正的聚合。更多的是过滤:

select distinct d.*
from datas d
where d.caseId is not null or
      not exists (select 1
                  from datas d2 
                  where d2.userid = d.userid and d2.caseid is not null
                 );

这是一把小提琴。

zujrkrfu

zujrkrfu2#

我从@gordonlinoff查询开始,将其更改为获得以下结果:

select distinct d.*
from datas d
where d.caseId is not null or
      not exists (select 1
                  from datas d2 
                  where d2.id = d.id and d2.userid = d.userid and d2.caseid is not null
                 );

我把条件加在 d2.id = d.id

相关问题