我正在处理我输入的一个很大的查询,但是在这里我将其缩短。我想做的是选择一堆列,然后运行when并使用where not in子句来过滤结果,以便仅查看用户的授权。如果我从where子句中删除PERM NOT IN,它将返回授权和未授权用户的身份,而我不希望看到该情况。我不是100%不确定是否有可能,是否可以通过其他方式或更简单的方式来完成该工作,这是很好的。
这是我的查询:
SELECT
usname AS Name, ususer AS Username, usseclevel AS Default_Level,
usglsecl AS GL_SecurityLevel, aoopid, aoseclevel
CASE
WHEN aoauopid >= 00500 AND aoAuOpID < 10000
THEN
CASE
WHEN usglsecl >= aoseclevel
THEN 'Authorized'
ELSE 'Unauthorized'
END
END AS PERM
FROM
library.file
JOIN
library.file ON usseclevel >= aoseclevel
WHERE
ususer NOT IN ('*ALL', 'daffron')
AND PERM NOT IN ('Unauthorized, 'null')
ORDER BY
ususer
如果您希望我发布整个查询,则可以,但是我认为它不需要整个查询才能获得所需的输出。
答案 0 :(得分:4)
由于我不确定您使用的是哪种SQL变体,因此我将不知所措。您通常不能在WHERE
子句中使用列别名。在我头顶上方,我看到了三个选项:
选项1-使用“表表达式”从别名中产生一个真实的列名:
select * from (
Select usname as Name, ususer as Username, usseclevel as Default_Level,
usglsecl as GL_SecurityLevel, aoopid, aoseclevel
Case When aoauopid >=00500 and aoAuOpID <10000 then case when
usglsecl>=aoseclevel then 'Authorized' else 'Unauthorized' end END AS PERM
from library.file join library.file on usseclevel>=aoseclevel
WHERE ususer NOT IN('*ALL','daffron')
) x
WHERE PERM NOT IN('Unauthorized,'null')
ORDER BY ususer
选项2-使用CTE(公用表表达式):
with x as (
Select usname as Name, ususer as Username, usseclevel as Default_Level,
usglsecl as GL_SecurityLevel, aoopid, aoseclevel
Case When aoauopid >=00500 and aoAuOpID <10000 then case when
usglsecl>=aoseclevel then 'Authorized' else 'Unauthorized' end END AS PERM
from library.file join library.file on usseclevel>=aoseclevel
WHERE ususer NOT IN('*ALL','daffron')
)
select * from x
WHERE PERM NOT IN('Unauthorized,'null')
ORDER BY ususer
选项3-在WHERE子句中(而不是PERM)再次重复整个CASE:
Select usname as Name, ususer as Username, usseclevel as Default_Level,
usglsecl as GL_SecurityLevel, aoopid, aoseclevel
Case When aoauopid >=00500 and aoAuOpID <10000 then case when
usglsecl>=aoseclevel then 'Authorized' else 'Unauthorized' end END AS PERM
from library.file join library.file on usseclevel>=aoseclevel
WHERE ususer NOT IN('*ALL','daffron')
and Case When aoauopid >=00500 and aoAuOpID <10000 then case when
usglsecl>=aoseclevel then 'Authorized' else 'Unauthorized' end END
NOT IN('Unauthorized,'null')
ORDER BY ususer