排除已删除哪些特定值的用户ID

时间:2017-10-30 09:41:38

标签: sql

如果用户与特定广告系列进行了互动,我需要排除用户ID(在本例中为Campaign_ID 4)。

User_ID | Campaign_ID| Value1| Value 2, Value 3, etc.
--------|------------------------------------       
|  1    | Campaign_1 | 1     |               |
|  1    | Campaign_4 | 1     |               |
|  2    | Campaign_1 | 1     |               |
|  3    | Campaign_1 | 1     |               | 
|  3    | Campaign_2 | 1     |               |
|  3    | Campaign_3 | 1     |               | 
|  4    | Campaign_1 | 1     |               |
|  4    | Campaign_4 | 1     |               |
|  5    | Campaign_3 | 1     |               |
---------------------------------------------

我尝试了以下查询,以某种方式排除与Campaign_ID 4进行过互动的所有User_ID:

SELECT DISTINCT *
FROM Report_1
WHERE Campaign_ID IN ("1", "2", "3")
  AND User_ID NOT IN (SELECT User_ID FROM Report_1 WHERE Campaign_ID IN ("4"))

但是,查询仅删除campaign_ID为4的行:

User_ID | Campaign_ID| Value1| Value 2, Value 3, etc.
--------|------------------------------------       
|  1    | Campaign_1 | 1     |               |
|  2    | Campaign_1 | 1     |               |
|  3    | Campaign_1 | 1     |               | 
|  3    | Campaign_2 | 1     |               |
|  3    | Campaign_3 | 1     |               | 
|  4    | Campaign_1 | 1     |               |
|  5    | Campaign_3 | 1     |               |
----------------------------------------------

我希望看到包含与Campaign_ID 4交互的User_ID的所有行都会消失(在本例中为User_ID 1和4)。

User_ID | Campaign_ID| Value1| Value 2, Value 3, etc.
--------|------------------------------------       
|  2    | Campaign_1 | 1     |               |
|  3    | Campaign_1 | 1     |               | 
|  3    | Campaign_2 | 1     |               |
|  3    | Campaign_3 | 1     |               | 
|  5    | Campaign_3 | 1     |               |
---------------------------------------------

有没有办法设置执行此操作的查询?

谢谢!

@ EDIT:我在表中添加了另一列(真实表包含30个不同的列)

1 个答案:

答案 0 :(得分:0)

如果您的compaign_id列包含针对compaign_id 1的 Campaign_1 ,针对compaign_id 2等 Campaign_2 ,则以下查询将满足您的要求

SELECT DISTINCT *
FROM Report_1
WHERE User_ID NOT IN 
(SELECT User_ID FROM Report_1 WHERE Campaign_ID = 'Campaign_4');