sql查询分组与聚合

时间:2017-03-27 14:20:40

标签: mysql count group-by sum aggregate

以下表为例:

    zipcode |  zipsource | patientcount
    -----------------------------------
     81501  |     CMHSP  |   10
     81503  |     CMHSP  |   20
     81505  |     CMHSP  |   30
     81501  |     SMHRMC |   15
     81503  |     SMHRMC |   25
     81505  |     SMHRMC |   35

试图仅显示患者数量超过源和源的总数的20%的拉链码= SMHRMC(通常是参数,但我选择了SMHRMC的例子)。输出表如下:

   zipcode  | zipsource  |  patientcount | Total  | Percent
   --------------------------------------------------------
    81503   |  SMHRMC    |   25          |  75    |  25%
    81505   |  SMHRMC    |   35          |  75    |  47%

我尝试过多次查询,但此时我认为我并不接近。有任何想法吗?

有效的查询如下:

    select zipcode, 
           zip_source, 
           patient_count, 
           total_count, 
           patient_count *100/total_count as percentage
    from Zip_Count_Source
    cross join (select sum(patient_count) as total_count
                from zip_count_Source
                where zip_source = 'COMHSP') as X
    where zip_source = 'COMHSP' and  patient_count*100/total_count > 1

但我现在遇到的问题是Zip_source可以是一个多值参数,所以我将子句更改为zip_source('COMHSP','SMHRMC')并且它可以工作,但我想为每个源提供total_count但不是两个来源的合并。在by子句之后,Group By没有工作。感谢所有帮助过的人。

3 个答案:

答案 0 :(得分:0)

这应该可以解决问题

select  t1.zipcode,
        t1.zipsource,
        t1.patientcount,
        t2.total,
        t1.patientcount / t2.total * 100 as percent
from    yourTable t1
join    (
            select  zipcode, sum(patientcount) as total
            from    yourTable
            group by zipcode
        ) t2
on      t1.zipcode = t2.zipcode
where   t1.patientcount / t2.total > 0.2

要过滤单个zipsource,您可以为where子句添加条件

where   t1.patientcount / t2.total > 0.2 and
        t1.zipsource = 'SMHRMC'

答案 1 :(得分:0)

试试这个:

SELECT zipcode, zipsource, patientcount * 100 / total_count
FROM mytable
CROSS JOIN (SELECT SUM(patientcount) AS total_count
            FROM mytable
            WHERE zipsource = 'SMHRMC') AS x
WHERE zipsource = 'SMHRMC' AND patientcount / total_count > 0.2

该查询使用CROSS JOIN来将patientcount的总计数与表格相关联。使用此计数,我们可以计算百分比,并过滤掉任何不超过所需值的行。

Demo here

答案 2 :(得分:0)

当连接到另一个表时,通常会有一个连接条件来过滤掉阻止笛卡尔积的行(一个表的内容乘以另一个表)。由于派生表(total)返回单个值,因此不需要连接条件(table1的内容乘以1 = table1)。

只要该值代表您想表达的内容(即删除where条件并且它将产生所有患者的总数),这是可以接受的。

select zipcode,
       zipsource,
       sum(patientcount) as patientcount,
       Total,
       concat(round(100*sum_patientcount/Total),'%') as `SHRMC_%`
  from table1,
       (select count(*) as Total
          from table1
         where zipsource='SHRMC') as total
 where zipsource='SHRMC'
 group by zipcode
   having sum(patientcount)/total >= .2