根据条件选择单行

问题描述 投票:0回答:1

我有一些麻烦,如果重复或基于某些条件,只能检索一行。

假设我有一张这样的桌子:

数据:

+-----+---------+------------+
| 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为NOT NULL的行。

如果一个userId有两行或更多行,caseId不为null且它们之间不同,我需要保留所有这些。当然,如果我也有NULL行,我将不考虑它们。

希望现在更加清晰。

sql sql-server azure-sql-database
1个回答
0
投票

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

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
                 );

Here是db <>小提琴。

© www.soinside.com 2019 - 2024. All rights reserved.