2016-12-29 65 views
0

我有3個表SQL - 如何獲取每個不同值的計數?

**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

嗯。 。 。

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
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. 
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 

LEFT JOIN等你發現房間沒有護士調度。
計數(不同的ns.nurse_schedule_id)如果需要看看有多少不同的護士組成計數。

通常你也有時間組件。就像「其中r.roomdate = ns.date」

相關問題