在两列的基础上执行查询

时间:2019-02-07 10:20:27

标签: sql sql-server case

这是我要在其中基于两列执行查询的表。我想基于第一列值执行查询。如果放在case statement的where子句中,则必须选择第一列的值。

id  | Service
-------------
123 | 4
124 | 4
125 | 3
126 | 6
-------------
     Select Service
    case when Service = 4 then (select size from table1 where id = {first column value})
    case when Service = 3 then (select size from table2 where id = {first column value})
    case when Service = 6 then (select size from table3 where id ={first column value})
    End as
    Size 
    From Services_table

2 个答案:

答案 0 :(得分:0)

我认为,只要将{first column value}替换为id,您的查询就会起作用,如下所示:

SELECT Service,
    CASE
        WHEN Service = 4 THEN (SELECT Size FROM Sizes1 WHERE Id = Id)
        WHEN Service = 5 THEN (SELECT Size FROM Sizes2 WHERE Id = Id)
        WHEN Service = 6 THEN (SELECT Size FROM Sizes3 WHERE Id = Id)
    END AS Size 
FROM Services_Table

但是,JOIN's are (usually) preferable是子查询,因此您可以重写此查询:

SELECT Service,
    CASE
        WHEN Service = 4 THEN S1.Size
        WHEN Service = 5 THEN S2.Size
        WHEN Service = 6 THEN S3.Size
    END AS Size 
FROM Services_Table S
LEFT JOIN Sizes1 S1 ON S.Id = S1.Id
LEFT JOIN Sizes2 S2 ON S.Id = S2.Id
LEFT JOIN Sizes3 S3 ON S.Id = S3.Id

话虽如此,我要重申上面的评论,即这样的查询通常表示设计选择存在问题,您应该考虑重新设计数据结构。

答案 1 :(得分:0)

我想您只需要一个相关的子查询。为此,您需要适当的合格列名称:

Select Service
       (case when Service = 4
             then (select t1.size from table1 t1 where t1.id = st.id)
             when Service = 3
             then (select t1.size from table1 t2 where t2.id = st.id)
             when Service = 6
             then (select t3.size from table1 t2 where t3.id = st.id)
        end) as Size 
From Services_table st