在SELECT部分​​查询中使用IF

时间:2016-09-26 11:25:04

标签: sql-server

我需要创建像这样的东西

SELECT x.id
   , x.name
   , x.type
   ,(
      IF x.type = 1
         (SELECT SUM(Col1) FROM TableA WHERE ... etc)
      ELSE IF x.type = 2
         (SELECT SUM(Col2) FROM TableB WHERE ... etc)
    ) AS Total
FROM TableX as x

所以我试图根据x.type

的值选择不同的子查询

5 个答案:

答案 0 :(得分:2)

尝试使用LEFT JOINCOALESCE。使用x.type的条件加入表格。

  

COALESCE(Transact-SQL):按顺序计算参数,并返回最初未计算为NULL的第一个表达式的当前值。   https://msdn.microsoft.com/en-us/library/ms190349.aspx

SELECT x.id
   , x.name
   , x.type
   , COALESCE(SUM(TableA.Column), SUM(TableB.Column)) as column_xyz
FROM TableX as x
LEFT JOIN TableA ON x.type = 1 AND ...
LEFT JOIN TableB ON x.type = 2 AND ...

您还可以使用CASE WHEN ... THEN ...代替COALESCE来定义要使用的列。

答案 1 :(得分:1)

您可以使用CASE WHEN,如下所示:

SELECT 
    x.id, 
    x.name, 
    x.type,
    CASE 
        WHEN x.type = 1 THEN (SELECT SUM(A.Col1) FROM TableA A WHERE 1 = 1)
        WHEN x.type = 2 THEN (SELECT SUM(B.Col2) FROM TableB B WHERE 1 = 1)
        ELSE NULL END AS Total
FROM 
    TableX as x

答案 2 :(得分:1)

使用CASE声明

SELECT x.id,
       x.name,
       x.type,
       CASE
         WHEN x.type = 1 THEN (SELECT Sum(Col1)
                               FROM   TableA Where...)
         WHEN x.type = 2 THEN (SELECT Sum(Col2)
                               FROM   TableB  Where .. )
       END AS Total
FROM   TableX AS x 

答案 3 :(得分:1)

您可以使用case expression

select t.* ,
            Case when t.type = 1 then (select sum(col1) ... TableA)
                      when t.type = 2 then (select sum(col2) ... TableB)
             End as Total
From tableX t

答案 4 :(得分:0)

使用变量 -

DECLARE @SumA INT = SELECT SUM(Col1) FROM TableA WHERE ... etc
DECLARE @SumB INT = SELECT SUM(Col2) FROM TableB WHERE ... etc

SELECT x.id
   , x.name
   , x.type
   ,( CASE x.type
        WHEN 1 THEN @SumA
        WHEN 2 THEN @SumB
      END
    ) AS Total
FROM TableX as x

相应地选择Sum变量的数据类型(如果是Decimal)。