简体   繁体   English

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

[英]MySQL select and count 2 colums with different where clauses

I think it should be very easy, but it didn't work at all. 我认为应该很容易,但它根本不起作用。 I have one table and I'd like to generate a chart which are displaying grouped items and with one where clause (column1) it should display the entries with status 0, and with the other where clause (column2) it should display the entries with status 1. 我有一个表,我想生成一个显示分组项目的图表和一个where子句(column1)它应该显示状态为0的条目,而另一个where子句(column2)它应该显示条目状态1。

If I do the just one query it works fine, but I'd like to have both (status 0 and status 1) in one combined query. 如果我只做一个查询它工作正常,但我想在一个组合查询中同时具有(状态0和状态1)。

Status 0 query: 状态0查询:

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

Status 1 query: 状态1查询:

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

My try to combine both (didn't work) 我尝试将两者结合起来(不起作用)

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

check this please , would it work for you? 请检查一下,它会对你有用吗?

please try this 请试试这个

 SELECT
    item,quantity,
    COUNT(case when status =1 then 1 end) AS status1,
    COUNT(case when status =0 then 1 end) AS status0
  FROM table

SQL Fiddle Testdata: SQL小提琴测试数据:

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')
;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM