我在下面运行了查询
SELECT
SUBSTRING_INDEX(prim_key ,":" , 1) prim_key,
SUBSTRING_INDEX(prim_key ,":" , -1) urid,
CASE WHEN basicname = 'Q914' THEN 'SHC'
WHEN basicname = 'QP913' THEN 'PHC'
WHEN basicname = 'QC1214' THEN 'CHC'
WHEN basicname = 'QD1014' THEN 'DH/SDH'
ELSE 'UNKOWN'
END AS Status
FROM facility_data
WHERE 1 = 1
AND basicname in ( 'Q914' , 'QP913' , 'QC1214' , 'QD1014' )
and prim_key like '3_10_%'
ORDER BY prim_key ASC
我需要略微修改,我希望它显示SHC,DH,PHC和CHC的总数。
所以请告诉我怎么做才能显示shc,dh,phc和chc的总数。
答案 0 :(得分:1)
SELECT status
, Count(*)
FROM (
SELECT CASE basicname
WHEN 'Q914' THEN 'SHC'
WHEN 'QP913' THEN 'PHC'
WHEN 'QC1214' THEN 'CHC'
WHEN 'QD1014' THEN 'DH/SDH'
END AS status
FROM facility_data
WHERE basicname in ('Q914', 'QP913', 'QC1214', 'QD1014' )
AND prim_key like '3_10_%'
) As x
GROUP
BY status
如果您希望按prim_key
和urid
分组
SELECT prim_key
, urid
, status
, Count(*)
FROM (
SELECT SUBSTRING_INDEX(prim_key, ':', +1) As prim_key
, SUBSTRING_INDEX(prim_key, ':', -1) As urid
, CASE basicname
WHEN 'Q914' THEN 'SHC'
WHEN 'QP913' THEN 'PHC'
WHEN 'QC1214' THEN 'CHC'
WHEN 'QD1014' THEN 'DH/SDH'
END AS status
FROM facility_data
WHERE basicname in ('Q914', 'QP913', 'QC1214', 'QD1014' )
AND prim_key like '3_10_%'
) As x
GROUP
BY prim_key
, urid
, status
答案 1 :(得分:0)
如果仅使用计数获得一行(您使用SUM
),则可以在IF
内部使用where
语句。
SELECT
sum(if(basicname = 'Q914',1,0)) as SHC,
sum(if(basicname = 'QP913',1,0)) as PHC,
sum(if(basicname = 'QC1214',1,0)) as CHC,
sum(if(basicname = 'QD1014',1,0)) as DH
FROM facility_data
WHERE
basicname in ( 'Q914' , 'QP913' , 'QC1214' , 'QD1014' )
and prim_key like '3_10_%'
ORDER BY prim_key ASC
如果您想要多行(需要GROUP BY
),则使用Using temporary; Using filesort
:
SELECT
CASE WHEN basicname = 'Q914' THEN 'SHC'
WHEN basicname = 'QP913' THEN 'PHC'
WHEN basicname = 'QC1214' THEN 'CHC'
WHEN basicname = 'QD1014' THEN 'DH/SDH'
ELSE 'UNKOWN'
END AS Status,
COUNT(*) as `count`
FROM facility_data
WHERE
basicname in ( 'Q914' , 'QP913' , 'QC1214' , 'QD1014' )
and prim_key like '3_10_%'
GROUP BY basicname
ORDER BY prim_key ASC