如何在SQL查询中使用不等于CASE语句

时间:2015-11-20 11:06:20

标签: sql sql-server

我有一个查询,如下所示。请先看看这个查询。

SELECT 
    T3.[AcctName],
    SUM(T0.[DebLTotal]/85) AS buget,(Select sum(T3.[Debit]/85) From JDT1 T3 ) as 'CurrentBudget'
FROM 
    OBGT T0
INNER JOIN
    (SELECT 
         CASE 
            WHEN T1.[AcctName] LIKE '%Salaries%' THEN 'Salaries'
            WHEN T1.[AcctName] LIKE '%Travel%' THEN 'Travel'
            WHEN T1.[AcctName] LIKE '%Supplies%' THEN 'Supplies'
            WHEN T1.[AcctName] LIKE '%Consultants%' THEN 'Consultants'
            WHEN T1.[AcctName] LIKE '%Patient%' THEN 'Patient Care'
            WHEN T1.[AcctName] LIKE '%Equipment%' THEN 'Equipments' 
            WHEN T1.[AcctName] LIKE '%Expense%' THEN 'Other Expenses' 
            WHEN T1.[AcctName] LIKE '%Alteration%' THEN 'Alterations/Renovations'
            ELSE 'Alterations/Renovations'
         END as [AcctName],
         [AcctCode]
     FROM 
         OACT AS T1) AS T3 ON T0.[AcctCode] = T3.[AcctCode]
INNER JOIN 
    OBGS T2 ON T0.[Instance] = T2.[AbsId]
WHERE 
    T2.[Name] = 'Main Budget 2015'
GROUP BY 
    T3.[AcctName], T2.[Name]

在此查询中,您可以查看案例。我想在这里找到另一个专栏,因为如果AcctName与在案例中定义的任何一个列都不匹配,那么应该有另一个列,例如'其他费用' .eg,因为你可以看到所有别名,如果WHEN T1。[AcctName] LIKE'%薪水%'然后'薪水'和所有。我想要一些东西,如果T1。[AcctName]!=%薪水%,%顾问%,%费用%等等那么它应该是'其他费用'。我不知道该怎么做。请专家帮我解决这个问题。

2 个答案:

答案 0 :(得分:3)

或者我不了解你,或者只是改变你的ELSE

SELECT T3.[AcctName],
       SUM(T0.[DebLTotal]/85) AS buget,(Select sum(T3.[Debit]/85) From JDT1 T3 ) as 'CurrentBudget'
FROM OBGT T0
INNER JOIN
    (
    SELECT CASE WHEN T1.[AcctName] LIKE '%Salaries%' THEN 'Salaries'
                WHEN T1.[AcctName] LIKE '%Travel%' THEN 'Travel'
                WHEN T1.[AcctName] LIKE '%Supplies%' THEN 'Supplies'
                WHEN T1.[AcctName] LIKE '%Consultants%' THEN 'Consultants'
                WHEN T1.[AcctName] LIKE '%Patient%' THEN 'Patient Care'
                WHEN T1.[AcctName] LIKE '%Equipment%' THEN 'Equipments' 
                WHEN T1.[AcctName] LIKE '%Expense%' THEN 'Other Expenses' 
                WHEN T1.[AcctName] LIKE '%Alteration%' THEN 'Alterations/Renovations'
                ELSE 'Other Expenses'
           END as [AcctName],
           [AcctCode]
    from OACT AS T1
    ) as T3 ON T0.[AcctCode] = T3.[AcctCode]
INNER JOIN OBGS T2 ON T0.[Instance] = T2.[AbsId]
where T2.[Name] = 'Main Budget 2015'
GROUP BY T3.[AcctName],T2.[Name]

喜欢这个吗?

答案 1 :(得分:2)

如果你把那个放在ELSE条件下,它就可以工作!!!

ELSE 'Other Expenses'

最终,无论您在查询中使用NOT Equal还是ELSE,都会显示相同的结果。

如果您愿意在案例中使用NOT EQUAL,请使用此<>操作者。

更多参考资料...请参阅以下链接

https://social.msdn.microsoft.com/forums/sqlserver/en-US/0dff067e-7b8d-4b74-b123-978683caee0a/using-a-not-equal-in-sql-case-expression