【问题标题】:MySQL case when count distinct inside whereMySQL case when count distinct inside where
【发布时间】:2017-03-27 21:41:29
【问题描述】:

我正在尝试执行以下代码但出现错误

WHERE (case when (Count(distinct idc) >= 2) then idw NOT LIKE '%_pronto_' ELSE TRUE end) 

有时我有欺骗 'idc' 值,如果是这样,我想排除列 idw 具有类似 '%pronto' 的字符串的行

这些是查询的结果,我需要在外部查询中对其进行过滤:

# userid, idw,        uniq, idc
193,   q3470_pronto_, 0,   3470
193,   q3470_next_,   1,   3470
193,   q3496_alt_1_,  10,  34961
193,   q3498_alt_3_,  11,  34983
193,   q3499_alt_2_,  12,  34992

在上面的这种情况下,我想排除第 1 行,因为我有超过 1 个 idc = 3470 并且第 1 行的 idw 像 %pronto

我需要它,因为有时我有一个 uniq idc,我需要保持 pronto

【问题讨论】:

  • 你遇到了什么错误?
  • 错误码:1111. 组函数使用无效
  • 您不能在 WHERE 子句中使用像 COUNT() 这样的聚合函数。试试 HAVING。

标签: mysql count case distinct where


【解决方案1】:

这样的事情可以为你工作:

select *
from t
where find_in_set(uniq, (
            select group_concat(uniqs)
            from (
                select group_concat(case when t2.idw like '%\_pronto\_' then t2.uniq end) as uniqs
                from t t2
                group by userid,
                    idc
                having count(*) > 1
                ) t
            )) = 0;

Demo

【讨论】:

  • 实际上我无法选择表't',因为我的值是由子查询生成的。所以我有一个返回这个值的查询,我想在外部查询中过滤它
  • @Flib - 您可以将查询放在上述两个位置(t 之前),它应该可以工作。
  • 我认为它有效!但是我的查询太大了。不确定两次是否好。有什么想法吗?
  • @flib 我无法在没有实际查询的情况下发表评论
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-06-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-03-30
相关资源
最近更新 更多