SQL - 条件选择

时间:2017-09-26 19:41:33

标签: sql oracle conditional relational-database contain

我正在尝试构建一个Oracle SQL查询,我在其中选择包含至少一个License ='+'的用户,而所有Default Orgs =' - '。换句话说,选择具有没有默认组织的许可证的用户。在下面的例子中,我希望只有Annete才会显示在结果中。

Table_Users :用户,许可

Table_Organizations :Default_Org,Org_Name

以下查询不会返回任何结果:

select User 
from Table_Users, Table_Organizations 
where Table_Users.User = Table_Organizations.UsrX 
and (Default_Org = '+' and Default_Org = '-')*

Table Example

3 个答案:

答案 0 :(得分:0)

select User 
from Table_Users, Table_Organizations 
where Table_Users.User = Table_Organizations.UsrX 
and License = '+' and Default_Org = '-'

答案 1 :(得分:0)

SELECT
    u.User
FROM
    Table_Users u
    INNER JOIN Table_Organizations o
    ON u.User = o.Usrx
GROUP BY
    u.User
HAVING
    COUNT(CASE WHEN License = '+' THEN 1 END) > 0
    AND COUNT(CASE WHEN Default_Org = '+' THEN 1 END) = 0

首先,我建议使用Explicit not Implicit join,这是我的一个宠儿,我认为这个网站上的许多其他人作为Explicit join已经成为ANSI SQL标准的一部分已经很多年了。

至于你真正想要的技术将被称为条件聚合。通过仅计算您要查找的值,您可以在HAVING子句中使用它们来排除您不想要的记录。

注意COUNT(CASE WHEN... THEN END)将起作用,因为只有您想要的值才会计算值,任何不符合该条件的值都将为NULL,因此不计算在内。

因为我不知道哪个表上有许可证,所以您也可能使用如下:

SELECT
    u.User
FROM
    Table_Users u
WHERE
    u.License = '+'
    AND NOT EXISTS(SELECT 1 FROM Table_Organizations o WHERE u.User = o.Usrx AND Default_Org = '+')

答案 2 :(得分:0)

知道+之前 - 我们可以使用最小聚合。这假定许可证和默认组织只能有'+'或' - '值。

With cte ("user", license, default_org, org_name) as  (
SELECT 'Jeff','+','+', 'Org 1' FROM DUAL UNION ALL
SELECT 'Jeff','-','-', 'Org 2' FROM DUAL UNION ALL
SELECT 'Jeff','-','-', 'Org 3' FROM DUAL UNION ALL
SELECT 'Annete','+','-', 'Org 4' FROM DUAL UNION ALL
SELECT 'Annete','-','-', 'Org 5' FROM DUAL)

SELECT "user", min(license), Min(default_org) 
FROM CTE A
GROUP BY "user"
HAVING min(license) = '+' 
   AND min(Default_org) = '-';

如果license和default_org都有用户索引;这会非常快。

相关问题