您的 ROLLUP 已经正确,这确实COUNT(CASE WHEN Field = 'Blah' THEN 1 ELSE 0 END)
是您的查询不起作用的主要原因
您必须执行以下任一操作:
COUNT(CASE WHEN Field = 'Blah' THEN 1 END)
或者
SUM(CASE WHEN Field = 'Blah' THEN 1 ELSE 0 END)
但是由于 MySQL 在布尔类型和整数类型之间具有双重性,就像在 C 语言中一样,因此您也可以这样做:
SUM(Field = 'Blah')
这是您的错误查询(错误结果):http ://www.sqlfiddle.com/#!2/70187/1
create table ProductInventory(
ProductCode varchar(10) not null,
Location varchar(50) not null
);
insert into ProductInventory(ProductCode,Location) values('CPU','US');
insert into ProductInventory(ProductCode,Location) values('CPU','US');
insert into ProductInventory(ProductCode,Location) values('CPU','CN');
insert into ProductInventory(ProductCode,Location) values('KB','CN');
insert into ProductInventory(ProductCode,Location) values('KB','JP');
insert into ProductInventory(ProductCode,Location) values('KB','US');
insert into ProductInventory(ProductCode,Location) values('MOUSE','US');
insert into ProductInventory(ProductCode,Location) values('MOUSE','CN');
不正确的输出:
PRODUCTCODE USQTY CHINAQTY
CPU 3 3
KB 3 3
MOUSE 2 2
8 8
这是正确的查询:http ://www.sqlfiddle.com/#!2/70187/2
select ProductCode,
COUNT(CASE WHEN Location = 'US' THEN 1 END) as UsQty,
COUNT(CASE WHEN Location = 'CN' THEN 1 END) as ChinaQty
from ProductInventory
group by ProductCode with rollup
正确的输出:
PRODUCTCODE USQTY CHINAQTY
CPU 2 1
KB 1 1
MOUSE 1 1
4 3
请不要坚持这是正确的,这是非常不正确的:
COUNT(CASE WHEN Location = 'US' THEN 1 ELSE 0 END) AS UsQty
您必须这样做(正确):
COUNT(CASE WHEN Location = 'US' THEN 1 END) AS UsQty
或者这个(正确):http ://www.sqlfiddle.com/#!2/70187/5
SUM(CASE WHEN Location = 'US' THEN 1 ELSE 0 END) AS UsQty
或者这个(正确):http ://www.sqlfiddle.com/#!2/70187/6
SUM(CASE WHEN Location = 'US' THEN 1 END) AS UsQty
或者尝试利用 MySql 在布尔和整数之间具有对偶性的事实(正确):http ://www.sqlfiddle.com/#!2/70187/4
SUM(Location = 'US') AS UsQty
底线
请不要使用这个(不正确):http ://www.sqlfiddle.com/#!2/70187/3
COUNT(Location = 'US') as UsQty
请不要也使用它(不正确,类似于您的查询):http ://www.sqlfiddle.com/#!2/70187/1
COUNT(CASE WHEN Location = 'US' THEN 1 ELSE 0 END) as UsQty
顺便说一句,这也有效,这是你找出原因;-)
COUNT(CASE WHEN Location = 'US' THEN 1976 END) AS UsQty
更新
我有一个暗示,这就是你需要的:
create table Product
(
ProductCode varchar(10) not null primary key,
ProductName varchar(100) not null
);
insert into Product(ProductCode,ProductName) values
('CPU','Central Processing Unit'),
('KB','Keyboard'),
('MSE','Mouse'),
('RAM', 'Random Access Memory');
create table ProductInventory(
ProductCode varchar(10) not null,
Location varchar(50) not null
);
insert into ProductInventory(ProductCode,Location) values
('CPU','US'),
('CPU','PH'),
('CPU','PH'),
('KB','PH'),
('KB','US'),
('KB','US'),
('MSE','US'),
('MSE','JP');
select p.ProductCode,
coalesce(SUM(i.Location = 'US'),0) as UsQty,
coalesce(SUM(i.Location = 'PH'),0) as PhilippinesQty
from Product p
left join ProductInventory i on i.ProductCode = p.ProductCode
group by p.ProductCode with rollup
输出:
ProductCode UsQty PhilippinesQty
CPU 1 2
KB 2 1
MSE 1 0
RAM 0 0
4 4
现场测试:http ://www.sqlfiddle.com/#!2/2bb09/1