我有这个SQL语句(已修改,因为真正的查询很大):
select tblInfo.IDNum, tblAddress.PrimaryAddress
from tblInfo
join tblAddress
on tblInfo.Agent = tblAddress.Agent
where (some stuff)
我得到的表格看起来大致如下:
|| IDNum || PrimaryAddress ||
-----------------------------
|| 01234 || 1 ||
|| 23456 || 1 ||
|| abcde || 0 ||
|| abcde || 1 ||
|| zyxwv || 0 ||
我需要一种方法来返回主要地址为1的所有记录,以及所有主要地址为0的记录,并且不要让IDNum返回主要地址为1.即在上面的示例中,(abcde || 0)应该被排除,因为(abcde || 1)存在。
答案 0 :(得分:2)
使用NOT EXISTS
SELECT tblInfo.IDNum, tblAddress.PrimaryAddress
FROM tblInfo
INNER JOIN tblAddress
ON tblInfo.Agent = tblAddress.Agent
WHERE tblAddress.PrimaryAddress = 1
OR ( tblAddress.PrimaryAddress = 0 AND NOT EXISTS
(
SELECT 1 FROM tblInfo t2 INNER JOIN tblAddress a2 ON t2.Agent = a2.Agent
WHERE t2.IDNum = tblInfo.IDNum AND a2.PrimaryAddress = 1
)
)
答案 1 :(得分:1)
在这种情况下,简单的GROUP BY
应该适用于您要执行的操作。实际上,您希望所有IDNum值都显示一次,其中PrimaryAddress值对应于最高值(如果存在,则为1,如果不存在则为0)。
假设您需要保留原始查询,因为您正在使用它进行其他工作,您可以使用:
SELECT IDNum, MAX(PrimaryAddress) AS PrimaryAddress
FROM
(
select tblInfo.IDNum, tblAddress.PrimaryAddress
from tblInfo
join tblAddress
on tblInfo.Agent = tblAddress.Agent
where (some stuff)
)
GROUP BY IDNum
这应该适用于MS SQL Server和Oracle,不确定其他DBMS。如果嵌套查询在您正在使用的DBMS中不起作用,您应该能够使用第一个查询的结果填充临时表,然后对该表执行分组。
答案 2 :(得分:0)
我希望这会有所帮助
select * from tblAddress mainTBL
where mainTBL.primaryaddress = (Case when EXISTS(select t1.IDNUM from tblAddress t1 where
mainTBL.IDNUM = t1.IDNUM AND t1.primaryAddress = 1) THEN 1 ELSE 0 END)