使用条件计数过滤GROUP BY中的查询结果

时间:2014-01-30 04:41:35

标签: mysql sql select group-by having-clause

我有以下架构http://sqlfiddle.com/#!2/1241f9/9

第一个查询显示我从表中收集的整个数据集。

我要做的是创建一个测试来检查网站上产品的显示但我希望它是动态的,因为当我们运行测试时,产品可能不再可用

为了做到这一点,我想找出哪个parent_id有超过3 child_id个,至少有一个child_id qty> 0,至少有一个child_id,其中qty = 0且wh_soh> 0并且至少有一个child_id qtywh_soh = 0。

这3个条件表明child_id可以在

中的3个状态
  • 有货(qty> 0)
  • 缺货但可以从仓库重新供应(qty = 0和wh_soh> 0)
  • 完全缺货(qtywh_soh = 0)

我可以过滤结果,以便获得具有3个或更多parent_id的所有child_id(第二个查询),下一步是执行{{1}之类的操作但是当我谷歌时,我一直在寻找计算组中唯一值的结果。

那么如何在我的查询中进行条件计数,即。 COUNT(WHERE qty = 0 AND wh_soh = 0)

2 个答案:

答案 0 :(得分:1)

尝试此查询,您可以使用SUM(条件)计算条件,如下所示

SELECT p.parent_id,
       COUNT(*) as children,
       SUM(c.qty > 0) as in_stock,
       SUM(c.qty = 0 AND c.wh_soh > 0) as warehouse,
       SUM(c.qty = 0 AND c.wh_soh = 0) as out_of_stock
FROM test_parent p 
INNER JOIN test_relation r USING (parent_id)
INNER JOIN test_child c USING (child_id)
GROUP BY p.parent_id
HAVING children > 3
   AND in_stock > 0
   AND warehouse > 0
   AND out_of_stock > 0

sqlFiddle

答案 1 :(得分:1)

试试这个:

SELECT a.parent_id, a.url 
FROM (SELECT tr.parent_id, tp.url, tr.child_id, 
            (CASE WHEN tc.qty > 0 THEN 1 WHEN tc.qty = 0 AND tc.wh_soh > 0 THEN 2 WHEN tc.qty = 0 AND tc.wh_soh = 0 THEN 3 END) AS test 
      FROM test_relation AS tr
      INNER JOIN test_parent AS tp ON tr.parent_id = tp.parent_id
      INNER JOIN test_child AS tc ON tc.child_id = tr.child_id
    ) AS a
GROUP BY a.parent_id HAVING COUNT(DISTINCT child_id) >=3 AND COUNT(DISTINCT test) >= 3;

点击此链接SQL FIDDLE DEMO

<强>输出

| PARENT_ID |   URL |
|-----------|-------|
|         5 | url_e |
|        11 | url_k |