从最高到最低分组

时间:2014-04-28 17:55:36

标签: mysql sql group-by sql-order-by

我有一张这样的表:

+---------+--------------+---------+
| visitty | specialty    | doctors |
+---------+--------------+---------+
| 1       | oncology     | 3611    |
| 1       | neurology    | 1931    |
| 1       | rheumatology | 1471    |
| 0       | oncology     | 35      |
| 0       | rheumatology | 28      |
| 0       | neurology    | 20      |
+---------+--------------+---------+

上表是通过对字段doctors

进行排序而创建的

现在,我试图获得以下结果:

+---------+--------------+---------+
| visitty | specialty    | doctors |
+---------+--------------+---------+
| 1       | oncology     | 3611    |
| 0       | oncology     | 35      |
| 1       | neurology    | 1931    |
| 0       | neurology    | 20      |
| 1       | rheumatology | 1471    |
| 0       | rheumatology | 28      |
+---------+--------------+---------+

有没有办法做到这一点?

回复Adil Miedl ......这些是查询中使用的标准: (PS:我认为如果没有引用的表格,对于未经处理的人来说可能有点混乱)

SELECT 
    su.visitty, cs.specialty, COUNT(*) doctors
FROM
    contacts c
INNER JOIN contact_groups ccgc ON c.id_contact = ccgc.id_contact
    AND ccgc.status = 1
INNER JOIN groups ccg ON ccg.id_ccenter_groups = ccgc.id_ccenter_groups
    AND ccg.status = 2
INNER JOIN distribuition ccd ON ccd.id_ccenter_groups = ccg.id_ccenter_groups
    AND ccd.status = 2
INNER JOIN cds_contacts sc ON c.id_cds_account = sc.id_cds_account
LEFT JOIN cds_contacts_territories AS sct ON sc.id_contact = sct.id_contact
INNER JOIN cds_usuarios_territories AS sut ON sut.id_territory = sct.id_territory
INNER JOIN cds_usuarios AS su ON su.id_user = sut.id_user
INNER JOIN contact_specialties cs ON c.id_contact = cs.id_contact
    and cs.status = 1
    and cs.srsmain = 'Y'
WHERE
    c.contact_type = 'Doctor'
        AND ccd.release_date BETWEEN '2013-01-01 00:00:00' AND '2013-12-31 23:59:59'
GROUP by visitty , cs.specialty
ORDER BY doctors DESC;

1 个答案:

答案 0 :(得分:0)

您似乎想要按照其中的医生总数订购专业。查询需要在执行排序之前计算此值:

select t.visitty, t.specialty, t.doctors
from table t join
     (select specialty, sum(doctors) as numdoctors
      from table t
      group by specialty
     ) tsum
     on t.specialty = tsum.specialty
order by tsum.doctors desc, tsum.specialty, t.doctors desc;