在SQL

问题描述:

查找具体数值我有一种情况,由此accountNo不是Primary Key,它有重复,我想搜索具有priority'0'值账户。 priority字段是varchar数据类型。下表是一个例子:在SQL

ID AccountNo Priority 
1 20   0 
2 22   0 
3 30   0 
4 20   1 
5 25   0 
6 22   0 

我想有价值'0',条件是在同一accountNo的其他副本没有任何价值priority'1'priority重复或accounts单记录。例如,accountNo 20有2条记录,但priority的值为'1',因此它不应该在输出中。对于accountNo 22,尽管它有2条记录,但都有priority的值为'0',因此它被认为是结果之一。

AccountNo 
    22 
    30 
    25 

我这里遇到的问题是,我只能用priority'0'发现账户,但这些账户是容易有重复accountNopriority价值'1'的可能性。下面的代码是什么我已经实现:

SELECT AccountNo 
FROM CustTable 
WHERE PRIORITY = '0' 
GROUP BY AccountNo 

如果Priority场发生在('0', '1')只值,那就试试这个:

SELECT AccountNo 
FROM CustTable 
GROUP BY AccountNo 
HAVING MAX(Priority) = '0' 

否则,你可以使用:

SELECT AccountNo 
FROM CustTable 
GROUP BY AccountNo 
HAVING COUNT(CASE WHEN Priority <> '0' THEN 1 END) = 0 
+0

我认为你的第二个查询应该是CASE WHEN Priority ='1'.. – sagi

返回AccountNo如果有优先级为0,但只有当不存在其他一行相同AccountNo拥有优先权1

SELECT DISTINCT AccountNo 
FROM CustTable t1 
WHERE PRIORITY = '0' 
and not exists (select * FROM CustTable t2 
       where t1.AccountNo = t2.AccountNo 
        and t2.PRIORITY = '1') 

无论您使用的RDBMS如何,这都可以正常工作,因为并非所有人都接受'group by'而没有选择聚合函数(例如, MAX())。 如果你提到你使用的RDBMS,那会更好。

SELECT DISTINCT tmp.AccountNo 
FROM 
    (SELECT AccountNo, MAX(Priority) 
    FROM CustTable 
    GROUP BY AccountNo 
    HAVING MAX(Priority) = '0' 
    ) tmp