SQL - 获取具有条件的每个不同值的计数?

时间:2016-12-31 15:04:25

标签: mysql sql select count

我有三张桌子

 **room**
    room_id | nurse_needed
    ----------------------
    1       | 3
    2       | 1
    3       | 2


**doctor_schedule**
    doctor_schedule_id| room_id | date     |shift
    -------------------------------------------------
           1          | 1       |12-30-2016|   1
           2          | 2       |12-31-2016|   2
           3          | 3       |12-30-2016|   2
           4          | 2       |12-30-2016|   2
*nurse_schedule*
    nurse_schedule_id | doctor_schedule_id
    --------------------------------------
    1                 |         1         
    2                 |         1         
    3                 |         3 

每个班次都有一名医生,每班需要一些护士。护士按照医生的时间表工作。我想知道在12-30-2016中有多少班子没有足够的护士。结果应该是:

    doctor_schedule_id| room_id | date     |shift | nurse_needed|nurse_have_in_room
   ------------------------------------------------------------------------------
           1          | 1       |12-30-2016|   1  |     3       |    2
           3          | 3       |12-30-2016|   2  |     2       |    1
           4          | 2       |12-30-2016|   2  |     1       |    0

2 个答案:

答案 0 :(得分:1)

您可以doctor_scheduleroom加入nurse_schedule汇总查询:

SELECT d.*, r.nurse_needed, n.nurses_in_room
FROM   doctor_schedule d
JOIN   room r ON d.room_id = r.room_id
JOIN   (SELECT   doctor_schedule_id, COUNT(*) AS nurses_in_room
        FROM     nurse_schedule
        GROUP BY doctor_schedule_id) n ON 
       d.doctor_schedule_id = n.doctor_schedule_id AND
       r.nurse_needed > n.nurses_in_room

答案 1 :(得分:1)

您可以INNER JOIN这样的所有表格,并过滤掉所需数量的护士少于或等于已经存在的数量的那些。

select d.doctor_schedule_id,
    d.room_id,
    d.date,
    d.shift,
    r.nurse_needed,
    COUNT(distinct n.nurse_schedule_id) nurse_have_in_room
from doctor_schedule d
inner join room r on r.room_id = d.room_id
left outer join nurse_schedule n on d.doctor_schedule_id = n.doctor_schedule_id
where d.date = '12-30-2016'
group by d.doctor_schedule_id,
    d.room_id,
    d.date,
    d.shift,
    r.nurse_needed
having r.nurse_needed > COUNT(distinct n.nurse_schedule_id);