我在下面给出了一个查询
SELECT A.order_no, A.order_date,
COUNT(B.reaction_no) as tot_reaction_no,
SUM(CASE
WHEN (B.purification != '') THEN 1
ELSE 0
END) as tot_purification
FROM order_header A
LEFT JOIN order_reactions B ON A.order_no = B.order_no
WHERE A.order_date BETWEEN '2015-10-01 00:00:00' AND '2016-09-01 00:00:00'
AND A.order_no = '23746'
GROUP BY A.order_no
这将产生如图所示的结果。但结果是错误的,因为有些条目是重复的。所以我必须删除副本并打印计数。所需的计数是表1中“列”的计数。
答案 0 :(得分:1)
我认为你需要在你的选择中省略A.order_date,或者你应该将它添加到group by子句中。这会给你一个不同的结果。
您也可以在select子句中使用子查询:
SELECT A.order_no, A.order_date,
COUNT(B.reaction_no) as tot_reaction_no,
(SELECT count(*) FROM order_reactions as or WHERE or.order_no=A.order_no AND purification!='') as tot_purification,
(SELECT count(*) FROM order_reactions as or2 WHERE or.order_no=A.order_no) as tot_reaction_no
FROM order_header A
WHERE A.order_date BETWEEN '2015-10-01 00:00:00' AND '2016-09-01 00:00:00'
AND A.order_no = '23746'
这只是我的头脑,因为你的截图没有显示完整的表格,我不确定这是100%正确,但它可能会指向正确的方向。
答案 1 :(得分:0)
我会提出查询
SELECT COUNT(DISTINCT clone_name) AS tot_purification, COUNT(*) AS tot_reaction_no FROM Table2 WHERE `purification`='Column' AND `order_no`=23746;
请原谅引用中的错误,在引用imo时,MySQL非常混乱。
编辑:
添加了AS tot_purification
我不确定你期望的是什么作为tot_reaction_no,所以我只计算了订单和净化匹配的所有行,如我的WHERE子句中所述。
答案 2 :(得分:0)
因为您只对 A.order_no 进行分组,请在查询中进行以下更改,然后重试:
替换行:
GROUP BY A.order_no;
到
GROUP BY A.order_no, A.clone_name;