SQL 查询以查找从中选择记录的同一个表
Posted
技术标签:
【中文标题】SQL 查询以查找从中选择记录的同一个表【英文标题】:SQL Query to lookup on same table from which selecting the records 【发布时间】:2019-03-05 11:59:55 【问题描述】:样本记录:
Custid pref_location
C1 PUNE
C1 MUMBAI
c1 DELHI
C2 PUNE
C2 MUMBAI
C3 MUMBAI
c4 PUNE
C5 DELHI
我想获取首选项位置仅为 PUNE 或 MUMBAI 的记录。我在以下查询的帮助下进行:
SELECT *
FROM EMP_PRE_LOCATION E1
WHERE EXISTS (SELECT 1
FROM EMP_PRE_LOCATION E2
WHERE E2.EID=E1.EID AND E2.PRE_LOCATION in ('PUNE','MUMBAI'))
AND NOT EXISTS (SELECT 1
FROM EMP_PRE_LOCATION E3
WHERE E3.EID=E1.EID AND E3.PRE_LOCATION NOT in('PUNE','MUMBAI'));
他们有更好的方法来达到同样的效果吗?
【问题讨论】:
【参考方案1】:我想你只是想要:
SELECT E1.*
FROM EMP_PRE_LOCATION E1
WHERE NOT EXISTS (SELECT 1
FROM EMP_PRE_LOCATION E2
WHERE E2.EID = E1.EID AND
E2.PRE_LOCATION NOT IN ('PUNE', 'MUMBAI')
);
如果您只希望员工在这两个位置,那么您可以使用GROUP BY
和HAVING
:
SELECT E1.EID
FROM EMP_PRE_LOCATION E1
GROUP BY E1.EID
HAVING SUM(CASE WHEN E1.PRE_LOCATION NOT IN ('PUNE', 'MUMBAI') THEN 1 ELSE 0 END) = 0;
如果您想要位置列表,可以添加LISTAGG(E1.PRE_LOCATION, ',')
。
【讨论】:
【参考方案2】:请试试这个。
SELECT *
FROM EMP_PRE_LOCATION
WHERE pref_location ='PUNE' OR pref_location ='MUMBAI'
【讨论】:
【参考方案3】:第二个WHERE
子句可以满足你的要求:
SELECT E1.*
FROM EMP_PRE_LOCATION E1
WHERE E1.PRE_LOCATION IN ('PUNE','MUMBAI') AND
NOT EXISTS (SELECT 1
FROM EMP_PRE_LOCATION E3
WHERE E3.EID = E1.EID AND E3.PRE_LOCATION NOT IN ('PUNE','MUMBAI')
);
这将只返回EID
s,其中只有LOCATION IN ('PUNE','MUMBAI')
。
【讨论】:
嗨,Yogesh,感谢您的回复!来自 Gordon 的查询正在做同样的事情。我们不需要 E1.PRE_LOCATION IN ('PUNE','MUMBAI') 子句。以上是关于SQL 查询以查找从中选择记录的同一个表的主要内容,如果未能解决你的问题,请参考以下文章