SQL从IN()中的每个项目返回结果

时间:2013-05-08 12:53:23

标签: sql-server

你可以帮助我吗?

我提出了这个问题:

SELECT  DISTINCT(CAMPAIGN),
     count(STATUS)
FROM    
C18_101 INNER JOIN CLIENT_10 ON C18_101.ID = CLIENT_10.ID
WHERE CAMPAIGN in ('Batch 1','Batch 2','Batch 3','Batch 4','Batch 5') AND STATUS = 'Pending' 
GROUP BY  CAMPAIGN,STATUS

结果如下:

Batch 2     241

Batch 3     321

Batch 4     575

Batch 5     429

即使没有Batch1,我也需要Batch1的结果。

2 个答案:

答案 0 :(得分:3)

SELECT  CAMPAIGN,
     count(STATUS)
FROM    C18_101 
LEFT JOIN CLIENT_10 ON C18_101.ID = CLIENT_10.ID AND STATUS = 'Pending' 
WHERE CAMPAIGN in ('Batch 1','Batch 2','Batch 3','Batch 4','Batch 5') 
GROUP BY  CAMPAIGN

答案 1 :(得分:3)

SELECT
     X.CAMPAIGN,
     count(STATUS)
FROM
    (SELECT DISTINCT CAMPAIGN FROM C18_101) X
    LEFT JOIN
    CLIENT_10 C ON X.ID = C.ID AND C.STATUS = 'Pending' 
GROUP BY
    X.CAMPAIGN
  1. 您可以是GROUP BY或聚合,而不是两者
  2. 您在JOIN之前有所区别,以确保您的计数在每个CAMPAIGN中都是正确的
  3. 您真的需要广告系列过滤器吗?如果是,请添加到派生表X