MySQL选择并计算具有不同where子句的2个列

时间:2015-06-12 15:15:26

标签: mysql subquery

我认为它应该很容易,但它根本不起作用。我有一个表,我想生成一个显示分组项目的图表,并且有一个where子句(column1)它应该显示状态为0的条目,而另一个where子句(column2)它应该显示状态为1的条目。

如果我只做一个查询就可以了,但是我想在一个组合查询中同时拥有(状态0和状态1)。

状态0查询:

SELECT item,quantity, COUNT(status) FROM `table` 
WHERE `retry` = 1
AND `status` = 0
GROUP BY item,quantity
ORDER BY COUNT(status) DESC

状态1查询:

SELECT item,quantity, COUNT(status) FROM `table` 
WHERE `retry` = 1
AND `status` = 1
GROUP BY item,quantity
ORDER BY COUNT(status) DESC

我尝试将两者结合起来(没有工作)

SELECT t1.item,t1.quantity, COUNT(t2.status), COUNT(t3.status) FROM `table` AS t1
LEFT JOIN (SELECT item,status FROM `table` WHERE `status` = '0' AND `retry` = 1 GROUP BY item,quantity) AS t2
ON t1.ndc = t2.ndc
LEFT JOIN (SELECT item,status FROM `table` WHERE `status` = '1' AND `retry` = 1 GROUP BY item,quantity) AS t3
ON t1.ndc = t3.ndc
WHERE 1
GROUP BY t1.item,t1.quantity
ORDER BY COUNT(t2.status) DESC

2 个答案:

答案 0 :(得分:2)

请检查一下,它会对你有用吗?

请试试这个

android:groupIndicator="@null"

答案 1 :(得分:0)

SQL Fiddle Testdata:

CREATE TABLE testtable
    (`id` int, `item` bigint(15), `quantity` double,`status` int(2),`retry` int(2))
;

INSERT INTO testtable
    (`id`, `item`, `quantity`, `status`, `retry`)
VALUES
    (1, '452457824', '1.0', '1', '1'),
    (2, '452457824', '1.0', '1', '1'),
    (3, '452457824', '0.5', '1', '1'),
    (4, '452457824', '0.5', '0', '1'),
    (5, '452457824', '0.5', '0', '1'),
    (6, '452457824', '0.5', '0', '1'),
    (7, '21432423', '1.0', '1', '1'),
    (8, '21432423', '1.0', '1', '1'),
    (9, '21432423', '1.0', '0', '1'),
    (10, '21432423', '1.0', '0', '1'),
    (11, '3455467567', '2.0', '1', '1'),
    (12, '3455467567', '2.0', '1', '1'),
    (13, '3455467567', '2.0', '0', '1'),
    (14, '3455467567', '2.0', '0', '1'),
    (15, '3455467567', '2.0', '0', '1'),
    (16, '3455467567', '1.0', '1', '1'),
    (17, '3455467567', '1.0', '1', '1'),
    (18, '3455467567', '1.0', '1', '1')
;