简体   繁体   English

SQL查询 - 从表中选择不同的值

[英]SQL query - Selecting distinct values from a table

I have a table in which i have multiple entries against a FK. 我有一张桌子,其中我有一个针对FK的多个条目。 I want to find out the value of FK which do not have certain entries eg 我想找出没有特定条目的FK的值,例如
my table has following entries. 我的表有以下条目。

PK----------------FK-----------------Column entries

1----------------100-----------------ab1
2----------------100-----------------ab2
3----------------100-----------------ab4
4----------------200-----------------ab1
5----------------200-----------------ab2
6----------------200-----------------ab3
7----------------300-----------------ab1
8----------------300-----------------ab2
9----------------300-----------------ab3
10---------------300-----------------ab4

Now, from this table i want to filter all those FK which do not have ab3 or ab4 in them. 现在,从这张表中我想过滤所有那些没有ab3或ab4的FK。 Certainly, i expect distinct values ie in this case result would be FK= 100 and 200. 当然,我期望不同的值,即在这种情况下结果将是FK = 100和200。
The query which i am using is 我正在使用的查询是

select distinct(FK) 
from table1 
where column_entries != 'ab3' 
   or column_entries != 'ab4';

Certainly, this query is not fetching the desired result. 当然,此查询不会获取所需的结果。

try the following :- 尝试以下方法: -

select distinct fk_col from table1
minus
(select distinct fk_col from table1 where col_entry='ab3'
intersect
select distinct fk_col from table1 where col_entry='ab4')

This will show all those FKs which do not have 'ab3' and 'ab4'. 这将显示所有没有'ab3'和'ab4'的FK。 ie 100 and 200 in your case 即你的情况下100和200

The below script may be the solution if I got your question in a right way. 如果我以正确的方式得到你的问题,下面的脚本可能是解决方案。

SELECT DISTINCT(TableForeignKey)
FROM Test
WHERE TableForeignKey NOT IN (
SELECT T1.TableForeignKey
FROM Test T1 INNER JOIN Test T2 ON T1.TableForeignKey = T2.TableForeignKey
WHERE T1.TableEntry = 'ab3' AND T2.TableEntry = 'ab4')

SQLFiddle Demo SQLFiddle演示

You could use GROUP BY with conditional aggregation in HAVING: 您可以在HAVING中使用带有条件聚合的GROUP BY:

SELECT FK
FROM table1
GROUP BY FK
HAVING COUNT(CASE column_entries WHEN 'ab3' THEN 1 END) = 0
    OR COUNT(CASE column_entries WHEN 'ab4' THEN 1 END) = 0
;

The two conditional aggregates count 'ab3' and 'ab4' entries separately. 两个条件聚合分别计算'ab3''ab4'条目。 If both end up with results greater than 0, then the corresponding FK has both 'ab3' and 'ab4' and is thus not returned. 如果两者都以大于0的结果结束,则相应的FK具有'ab3''ab4' ,因此不返回。 If at least one of the counts evaluates to 0, then FK is considered satisfying the requirements. 如果至少有一个计数评估为0,则认为FK满足要求。

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

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