0

我在下面的查询中运行了这个

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 的总数。

4

2 回答 2

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
于 2013-09-13T10:14:49.003 回答
0

如果足够让您获得仅包含计数的一行(您使用的),则可以在内部使用SUMwith语句。IFwhere

 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),则使用 a:

 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
于 2013-09-13T10:26:23.747 回答