SQL - 如何获取每个不同值的计数?

时间:2016-12-29 03:01:42

标签: sql

我有3张桌子

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

   **doctor_schedule**
    doctor_schedule_id| room_id
    ---------------------------
           1          | 1
           2          | 2
           3          | 3

 *nurse_schedule*
    nurse_schedule_id | doctor_schedule_id
    --------------------------------------
    1                 |         1         
    2                 |         1         
    3                 |         2         

每个房间都需要一些护士,一名医生在室内工作,一名护士在医生的日程安排下工作。我想算一下每个房间有多少护士。 结果应该是:

room_id     | nurse_needed|nurse_have_in_room
---------------------------------------------
    1       | 2           | 2
    2       | 3           | 1
    3       | 1           | 0

3 个答案:

答案 0 :(得分:3)

嗯。嗯。 。

select r.*,
       (select count(*)
        from doctor_schedule ds join
             nurse_schedule ns
             on ds.doctor_schedule_id = ns.doctor_schedule_id
        where ds.room_id = r.room_id
       ) as nurse_have_in_room
from room r;

答案 1 :(得分:1)

select room.*,
(select count(*) from 
dotor_schedule docs,
nurse_schedule nurs
where docs.doctor_schedule_id=nurs.dcotor_schedule_id 
   group by docs.room_id) as nurse_have_in_room
from room;

 Result of join on doctor_schedule_id between doctor_schedule and  
 nurse_schedule

nurse_schedule_id | doctor_schedule_id   room_id
--------------------------------------+------------
1                 |         1         |    1
2                 |         1         |    1
3                 |         2         |    2

We group by room_id and then get the result.

答案 2 :(得分:1)

select r.room_id, 
r.nurse_needed, 
ns.nurses_scheduled,
ns.dist_nurses_scheduled
from room r
left join (select ds.room_id, 
           count(1) nurses_schedule,
           count(distinct ns.nurse_schedule_id) dist_nurses_scheduled
           from doctor_schedule ds
           join nurse_schedule ns
           on ds.doctor_schedule_id  = ns.doctor_schedule_id 
           group by ds.room_id) as ns
on r.room_id = ns.room_id

左连接,这样您就可以找到没有护士安排的房间 如果需要,计算(不同的ns.nurse_schedule_id)以查看有多少不同的护士组成计数。

通常你也有一个时间组件。像“where r.roomdate = ns.date”

之类的东西