WHEN条件基于当前行值

时间:2014-12-16 12:13:24

标签: sql sql-server database select case

在我的SELECT查询中,我想在CASE中为一个名为 IsActive 的值添加一个条件,以便在当前行的列类型中输入是" adhoc" 然后将IsActive的值设置为" n / a"。

SELECT CASE Type
            WHEN 'scheduled' THEN 'Scheduled'
            WHEN 'adhoc' THEN 'AdHoc'
            ELSE 'Unknown'
       END AS 'Type',
       CASE IsActive 
            WHEN (Type) = 'adhoc' THEN 'n/a'
            WHEN 0 THEN 'Stopped'
            WHEN 1 THEN 'Active'
       END AS 'Status'
FROM MyTable

但我在第WHEN (Type) = 'adhoc' THEN 'n/a'行上收到此错误:

  

' ='。

附近的语法不正确

如何根据当前行的条件做出决定?

5 个答案:

答案 0 :(得分:2)

您的第二个case基于一个列,然后您尝试在when中添加条件,这是不允许的:

CASE IsActive 
            WHEN (Type) = 'adhoc' THEN 'n/a'
            WHEN 0 THEN 'Stopped'
            WHEN 1 THEN 'Active'
       END AS 'Status'

我认为您打算这样做(使用不带列的case并将条件放在when中):

CASE 
WHEN [Type] = 'adhoc' THEN 'n/a'
WHEN IsActive = 0 THEN 'Stopped'
WHEN IsActive = 1 THEN 'Active'
END AS 'Status'

答案 1 :(得分:1)

试试这个:

SELECT (CASE Type
            WHEN 'scheduled' THEN 'Scheduled'
            WHEN 'adhoc' THEN 'AdHoc'
            ELSE 'Unknown'
        END) AS 'Type',
       (CASE 
            WHEN Type = 'adhoc' THEN 'n/a'
            WHEN IsActive = 0 THEN 'Stopped'
            WHEN IsActive = 1 THEN 'Active'
        END) AS 'Status'
FROM MyTable;

答案 2 :(得分:1)

Pedram jaan您的查询将是这样的:

SELECT CASE [Type]
            WHEN 'scheduled' THEN 'Scheduled'
            WHEN 'adhoc' THEN 'AdHoc'
            ELSE 'Unknown'
       END AS 'Type',
       CASE  
            WHEN [Type] = 'adhoc' THEN 'n/a'
            WHEN IsActive = 0 THEN 'Stopped'
            WHEN IsActive = 1 THEN 'Active'
       END AS 'Status'
FROM dbo.MyTable

使用类似括号的类型[类型]。这是一个关键字。

答案 3 :(得分:0)

SELECT CASE Type
        WHEN 'scheduled' THEN 'Scheduled'
        WHEN 'adhoc' THEN 'AdHoc'
        ELSE 'Unknown'
   END AS 'Type',
   CASE WHEN [Type] = 'adhoc' THEN 'n/a'                        
        WHEN IsActive = 0 THEN 'Stopped'
        WHEN IsActive = 1 THEN 'Active'
   END AS 'Status'
FROM MyTable

答案 4 :(得分:0)

MS Sql Server不支持当前计算的行操作。 要实现这个目标,你必须提到一个Cte

with cteType as (
SELECT CASE Type
            WHEN 'scheduled' THEN 'Scheduled'
            WHEN 'adhoc' THEN 'AdHoc'
            ELSE 'Unknown'
       END AS 'Type'
FROM MyTable)

select Type
,
       CASE IsActive 
            WHEN (Type) = 'adhoc' THEN 'n/a'
            WHEN 0 THEN 'Stopped'
            WHEN 1 THEN 'Active'
       END AS 'Status'
FROM cteType 

这将有效