SQL错误(having子句中的未知列)。

时间:2018-06-21 18:19:51

标签: mysql sql

[SQL]SELECT
vlog.lead_id, vlog.phone_number
FROM
vicidial_log as vlog
GROUP BY vlog.lead_id
HAVING(
CASE 
WHEN vlog.status = 'NA' THEN 1 
WHEN vlog.status = 'ADC' THEN 1 
END
) = COUNT(*)

[Err] 1054 - Unknown column 'vlog.status' in 'having clause'

上面的查询不起作用。我正在尝试实现这一目标:https://www.db-fiddle.com/f/ej4fM8GptBk9FvGJC8AkUH/0

 [SQL]SELECT
    vlog.lead_id, vlog.phone_number, vlog.status
    FROM
    vicidial_log as vlog
    GROUP BY vlog.lead_id
    HAVING(
    CASE 
    WHEN vlog.status = 'NA' THEN 1 
    WHEN vlog.status = 'ADC' THEN 1 
    END
    ) = COUNT(*)

这项工作可是没有给我我想要的结果

status =可以是任何值 lead_id =不唯一 phone_number =不唯一

我正在尝试查找状态至少为的电话号码

ADC
NA
OR BOTH ADC AND NA

任何其他组合都不应返回电话号码。

2 个答案:

答案 0 :(得分:2)

它是在黑暗中拍摄的,但也许对您有用。将您的HAVING子句更改为:

HAVING SUM(CASE WHEN vlog.status in ('NA','ADC') THEN 1 ELSE 0 END) = COUNT(*)

答案 1 :(得分:1)

这似乎可行:

SELECT DISTINCT lead_id, phone_number
FROM vicidial_log vlog
WHERE status IN ('NA', 'ADC')
AND NOT EXISTS (SELECT *
                FROM vicidial_log vlog2
                WHERE status NOT IN ('NA','ADC')
                AND vlog.lead_id = vlog2.lead_id
                AND vlog.phone_number = vlog2.phone_number)

虽然尚不确定100%是否需要同时在lead_idphone_number上进行比较。