LIKE 子句在 HAVING 子句中使用时不起作用

LIKE clause not working when used in a HAVING clause

这是我在 SQL 服务器中的查询。我想按以该子字符串“[PROS]”结尾的每个活动进行分组。

但是,我在最后包含的结果 table 有一些其他以“[RT]”结尾的

-- Metrics for Each Date & Specific Campaign
SELECT 
    campaign_name, 
    SUM(clicks) AS Total_Clicks
FROM 
    FB_Raw
GROUP BY 
    campaign_name
HAVING 
    campaign_name LIKE '%' + '[PROS]' + '%';

04_Remarketing_BOFU_3.31.2020 [RT]                      |  568
04_Remarketing_BOFU(optimize=PUR)_5.16.2020 [RT]        |  0
02_Prospecting_CBO_BidCaps_CH_6.29.20 [PROS]            |  2741
02_Prospecting_CostCaps0_5.12.2020 [PROS]            |  7549
04_Remarketing_Content_ATC/IC_4.10.2020 [RT]            |  478
04_Remarketing_Content_Visitors_4.30.2020 [RT]          |  381
04_Remarketing_MOFU_3.31.2020 [RT]                      |  2005
04_Remarketing_BOFU_CH_6.29.20 [RT]                     |  9
02_Prospecting_LC_Broad_Narrative [PROS]                |  6261
02_Prospecting_CBO_BidCaps_OGCreative_6.9.2020 [PROS]   |  1405
02_Prospecting_LC_Broad_6.30.2020 [PROS]                |  2512

您必须使用 ESCAPE character as the square brackets are used for Pattern matching when using LIKE。转义字符位于要使用其字面值的任何字符的前面。

HAVING should be used for filtering on an aggregate result. WHERE is for filtering the data before it is aggregated (when you are using aggregates). In your case you should use WHERE instead of HAVING.

SELECT campaign_name, 
       SUM(clicks) AS Total_Clicks
FROM FB_Raw
WHERE campaign_name LIKE '%![PROS!]%' ESCAPE '!'
GROUP BY campaign_name;

方括号在like子句中使用时具有特殊含义。在不转义的情况下,模式 %[PROS]% 匹配任何包含 PROS 的字符串。像这样转义方括号:

LIKE '%[[]PROS]%'