根据条件语句的结果,加入两个表中的一个

时间:2015-04-09 12:53:28

标签: sql sql-server

我有以下声明:

SELECT S.PRODUCTNAME AS PRODUCTNAME,
T.TARGET AS TARGETVALUE,
SUM(S.AMOUNT) AS AMOUNT,
COUNT(S.PRODUCTNAME) AS VOLUME
FROM #SALES S
INNER JOIN 

-- Here it all goes south
-- IF (some condition)
-- TABLE1
-- ELSE
-- TABLE2

所以我很清楚我要尝试实现的目标,如果满足某个条件,请加入TABLE1,另外还要加入TABLE2。虽然我知道语法不正确,但我甚至不确定这是否可行?

3 个答案:

答案 0 :(得分:0)

您可以使用left join,然后在SELECT

中选择正确的值
SELECT S.PRODUCTNAME AS PRODUCTNAME,
       COALESCE(T1.TARGET, T2.TARGET) AS TARGETVALUE,
       SUM(S.AMOUNT) AS AMOUNT, COUNT(S.PRODUCTNAME) AS VOLUME
FROM #SALES S LEFT JOIN 
     Table1 t1
     ON (some condition) LEFT JOIN
     Table2 t2
     ON (NOT (some condition))

答案 1 :(得分:0)

您必须像这样创建查询:

if (condition)

SELECT S.PRODUCTNAME AS PRODUCTNAME,
T.TARGET AS TARGETVALUE,
SUM(S.AMOUNT) AS AMOUNT,
COUNT(S.PRODUCTNAME) AS VOLUME
FROM #SALES S
INNER JOIN TABLE1 

else

SELECT S.PRODUCTNAME AS PRODUCTNAME,
T.TARGET AS TARGETVALUE,
SUM(S.AMOUNT) AS AMOUNT,
COUNT(S.PRODUCTNAME) AS VOLUME
FROM #SALES S
INNER JOIN TABLE2

或者您可以像这样使用动态SQL:

DECLARE @SQL NVARCHAR(MAX);

SELECT @SQL = 'SELECT S.PRODUCTNAME AS PRODUCTNAME,
    T.TARGET AS TARGETVALUE,
    SUM(S.AMOUNT) AS AMOUNT,
    COUNT(S.PRODUCTNAME) AS VOLUME
    FROM #SALES S
    INNER JOIN ' + CASE WHEN yourcondition THEN N'TABLE1 t' ELSE N'TABLE2 t' END
  + N' ON S.ID = t.ID';

EXEC sp_executesql @SQL;

答案 2 :(得分:0)

加入两个表,用例来选择要公开的字段。

select  S.PRODUCTNAME AS PRODUCTNAME,
        case when <condition> then t1.TARGET else t2.target end AS TARGETVALUE,
        SUM(S.AMOUNT) AS AMOUNT,
        COUNT(S.PRODUCTNAME) AS VOLUME
from    #SALES S
left join #Table1 t1
    on  t1.key = s.key
left join #Table2 t2
    on  t2.key = s.key;

我假设当条件指定T1时,T2可能根本不会加入,反之亦然,我会显示外连接。