简体   繁体   English

SQL:如何仅基于某些属性值选择不同的行

[英]SQL: How to select only distinct rows based on some property values

I have an sql-view in my database which uses a UNION to concat different results (one side contains a left join whereas the other side uses NULL as placeholder for the missing values). 我的数据库中有一个sql视图,它使用UNION合并不同的结果(一侧包含左联接,而另一侧则使用NULL作为缺失值的占位符)。 In one part of the join one of the properties (a foreign key) is null whereas in the other one it contains a value (for the same unique ID). 在联接的一部分中,属性之一(外键)为null,而在另一个联接中,它包含一个值(对于相同的唯一ID)。 So my join will give me a result set like this: 因此,我的加入将给我这样的结果集:

ID     |    ForeignKey
1           NULL
1           123
2           NULL
3           NULL
4           NULL
4           234

I try to reduce this result set to contain only entries with a unique ID, but I cannot check the ForeignKey against NULL because then I would filter out all other rows where the key is NULL. 我尝试将结果集减少为仅包含具有唯一ID的条目,但无法检查ForeignKey是否为NULL,因为这样我会过滤掉键为NULL的所有其他行。

What I am looking for is a way to tell SQL to check for the entire result set whether the same ID is used twice. 我正在寻找的是一种告诉SQL检查整个结果集是否使用相同ID两次的方法。 If it finds such a duplicate (as the entries with ID 1 and 4 above) it should only display the one with the value (123 and 234). 如果找到这样的重复项(如上面ID为1和4的条目),则应仅显示值(123和234)的重复项。 The entry with NULL should be filtered away. 带有NULL的条目应被过滤掉。

If no duplicate is found (as for ID 2 and 3) that entry should be used. 如果没有发现重复(如ID 2和ID 3),则应使用该条目。

So I want to transform the above result set to this: 所以我想将以上结果集转换为:

ID     |    ForeignKey
1           123
2           NULL
3           NULL
4           234

I tried to solve the problem by using the OVER keyword and PARTITION By ID where I set the RowNumber to be equal to 1. This filters away the duplicate entries however it chooses always the entry with NULL instead of the one with the actual key, so the WRONG result looks like this: 我试图通过使用OVER关键字和PARTITION By ID解决问题,其中将RowNumber设置为等于1。这可以过滤掉重复的条目,但是它总是选择NULL而不是带有实际键的条目,因此错误结果如下所示:

ID     |    ForeignKey
1           NULL
2           NULL
3           NULL
4           NULL
SELECT ID , MAX(ForeignKey) AS ForeignKey
FROM TableName
GROUP BY ID

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM