的MySQL> select * from products;
+---------+-------------+-----------+------+
| prod_id | prod_source | prod_type | flag |
+---------+-------------+-----------+------+
| 1 | USA | 2 | 0 |
| 2 | USA | 2 | 0 |
| 3 | USA | 2 | 0 |
| 4 | USA | 3 | 1 |
| 5 | USA | 3 | 0 |
| 6 | BRA | 1 | 1 |
| 7 | BRA | 2 | 1 |
+---------+-------------+-----------+------+
必需的结果:
+-----------+----------+
| prod_type | count(*) |
+-----------+----------+
| 2 | 3 |
| 3 | 0 |
| 4 | 0 |
+-----------+----------+
where condition
prod_source = USA
flag=0
但我得到的结果集是
+-----------+----------+
| prod_type | count(*) |
+-----------+----------+
| 2 | 3 |
+-----------+----------+
带有查询
SELECT prod_type ,count(*)
FROM products
WHERE prod_source='USA' and flag=0
GROUP by prod_type
ORDER by prod_type;
我如何获得美国所有prod_type的计数结果?即使计数为0,它也必须显示美国的所有prod_type。
表格定义:
CREATE TABLE `products` (
`prod_id` INTEGER UNSIGNED NOT NULL AUTO_INCREMENT,
`prod_source` VARCHAR(45) NOT NULL,
`prod_type` INTEGER UNSIGNED NOT NULL,
`flag` INTEGER UNSIGNED NOT NULL,
PRIMARY KEY (`prod_id`)
)
ENGINE = InnoDB;
数据插入:
INSERT INTO `products`
VALUES (1,'USA',2,0),
(2,'USA',2,0),
(3,'USA',2,0),
(4,'USA',3,1),
(5,'USA',4,1),
(6,'BRA',1,1),
(7,'BRA',2,1);
答案 0 :(得分:2)
在SQL Server中,我将使用以下内容:
SELECT prod_type,SUM(CASE WHEN flag=0 THEN 1 ELSE 0 END)
FROM products
WHERE prod_source='USA'
GROUP by prod_type
ORDER by prod_type
我不能说这是否适用于MySQL。
(Cheeky编辑以纠正SELECT子句中的列名)
答案 1 :(得分:0)
检查您的数据,查询是正确的,但顶部表中的数据与插入脚本不匹配(prod_id
5插入flag
= 1)
要获得0,您需要在当前查询中选择不同的prod_type
然后左连接。