根据条件选择单行

时间:2020-06-04 16:31:34

标签: sql sql-server azure-sql-database

在重复或基于特定条件的情况下,仅检索一行会给我带来麻烦。

假设我有一个这样的表:

数据:

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

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

希望现在更加清晰

EDIT2:

感谢@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
                 );

我在不存在的子查询中添加了一个条件,将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
                 );

现在我得到了我需要的东西。

谢谢大家!

2 个答案:

答案 0 :(得分:0)

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

Cloned the remote repo for the git url. Then the default remote branch showing local is say "D"
1 Created a new branch X
2 checkout X
3 did all the changes
4 added the files
5 Committed the files
6 and Did a rebase and pushed my branch to remote
7 And created a pull request

Here是db <>小提琴。

答案 1 :(得分:0)

我从@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上添加了条件