Question

I have a table like this:

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

The above table was created by ordering the field doctors

Now, I'm trying to get the following result:

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

Is there any way to do this?

In reply to Adil Miedl ... these were the criteria used in the query: (PS: I think it can be a little confusing to underestand without the referenced tables)

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;
Was it helpful?

Solution

You seem to want to order the specialties by the total of doctors in them. The query needs to calculate this value before doing the ordering:

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;
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top