带有ROLLUP的MySQL Sum(Total)和Sum(User)

时间:2012-10-31 04:22:54

标签: php mysql subquery sum rollup

我在使用复杂的MySQL查询时遇到了一些麻烦。我想从这个查询中获取3列。过程的名称,每个过程的站点总数以及每个过程的医师总数(用户总数)。我正在关联2个表格,procedurestbl_syn_procedure

只有一个条件可以让我的医生总数(用户总数)和procedures.phys_id = '##',但我不知道如何将其纳入查询。

我目前有一个大型查询,它提供了我需要的一半数据。

SELECT  
  IFNULL( Synoptic, 'Total Count') AS Synoptic, Total
FROM ( 
SELECT  
  Synoptic, 
  SUM( Data ) AS Total
FROM ( 
      SELECT 
        tbl_syn_procedure.name AS 'Synoptic',
        COUNT(*) AS Data
        FROM procedures 
        JOIN tbl_syn_procedure ON 
        procedures.proc_synoptic_id = tbl_syn_procedure.name_id 
        GROUP BY procedures.proc_synoptic_id 
     ) AS stats 
  GROUP BY Synoptic WITH ROLLUP
) AS stats

这给了我一个两列表,如下所示:

  

摘要--------------------------总计

     

APBI设备插入---------- 1328

     

MRI引导活检------------- 71

     

立体定向活组织检查------------- 10504

     

总计数---------------------- 11903

但是你可以看到它缺少了医生总数(用户总数)。如果有人能就如何将第三列添加到查询中给我一些建议。

1 个答案:

答案 0 :(得分:0)

试试这个

select
count(p.proc_synoptic_id), p.proc_synoptic_id, name, num_phys_procedures
from
procedures p
inner join tbl_syn_procedure on p.proc_synoptic_id = tbl_syn_procedure.name_id
left join
(
    select count(proc_synoptic_id) as num_phys_procedures, proc_synoptic_id from procedures
    where phys_id = ##
    group by proc_synoptic_id
) phys_procedures on p.proc_synoptic_id = phys_procedures.proc_synoptic_id

group by proc_synoptic_id, name;

它首先得到程序总数,然后连接到派生表phys_procedures,该表具有特定医生的程序数。