根据附加图像,我有两个表“VEHICLE”和“VEHICLE_CLASS”。
我需要一个查询来获取结果行,其中每个 VEHICLE_CLASS 按状态分组了多少 VEHICLES,如附图所示。
查询应该是通用的,以便可以在任何数据库(MySQL/Oracle/MSSQL/DB2)中使用
请帮忙。
CREATE TABLE VEHICLE
(
VEHICLE_ID varchar(20),
VEHICLE_CLASS_ID varchar(30),
STATUS int
);
CREATE TABLE VEHICLE_CLASS
(
VEHICLE_CLASS_ID varchar(30),
VEHICLE_CLASS_NAME varchar(30)
);
INSERT INTO VEHICLE
(VEHICLE_ID, VEHICLE_CLASS_ID, STATUS)
VALUES
('vehicle_001', 'vehicle_class_001', 0),
('vehicle_002', 'vehicle_class_002', 1),
('vehicle_003', 'vehicle_class_003', 2),
('vehicle_004', 'vehicle_class_001', 0),
('vehicle_005', 'vehicle_class_002', 2),
('vehicle_006', 'vehicle_class_001', 0),
('vehicle_007', NULL, 1);
INSERT INTO VEHICLE_CLASS
(VEHICLE_CLASS_ID, VEHICLE_CLASS_NAME)
VALUES
('vehicle_class_001', 'ABC'),
('vehicle_class_002', 'BCD'),
('vehicle_class_003', 'EFG');
这是我尝试但无法获得所需结果的查询:
SELECT veh.VEHICLE_CLASS_ID, vehclass.VEHICLE_CLASS_NAME,
SUM( CASE WHEN veh.STATUS=2 THEN COUNT(veh.VEHICLE_ID) end) Completed,
SUM( CASE WHEN veh.STATUS!=2 THEN COUNT(veh.VEHICLE_ID) end) not_completed
FROM VEHICLE veh LEFT JOIN VEHICLE_CLASS vehclass on veh.VEHICLE_CLASS_ID = vehclass.VEHICLE_CLASS_ID
GROUP BY veh.VEHICLE_CLASS_ID having veh.VEHICLE_CLASS_ID is not null;