根据总数获取当前状态

时间:2019-02-11 05:30:39

标签: mysql database database-design database-connection relational-database

我无法在mysql查询上建立条件(如果不是这样)。

简而言之,我有3个相互关联的表。

m_shift_schedule    site_shift_schedule      m_ticket
================    ===================     ============
* shift_id   ======> * shift_id             * ticket_id
* start_time         * shift_date           * ticket_status
* end_time           * user_id   ========>  * ticket_served_by

我现在的查询:

SELECT user_id
FROM site_shift_schedule
LEFT JOIN m_shift_schedule ON site_shift_schedule.shift_id = m_shift_schedule.shift_id
WHERE site_shift_schedule.shift_date =  '2019-02-11';

enter image description here

如果我想让输出变成这样,该怎么办?

空闲= m_ticket.ticket_status(4或5或6),总点数m_ticket.ticket_served_by <2

繁忙= m_ticket.ticket_status(4或5或6),总点数m_ticket.ticket_served_by = 2

过载= m_ticket.ticket_status(4或5或6),总点数m_ticket.ticket_served_by> 2

      user_id                           Status
  =============================       ============
 ismail.rahman.saanin@random.co          Idle
 lutfi.aldi.nugroho@random.co            Busy

帮我,谢谢。 。

1 个答案:

答案 0 :(得分:0)

您可以尝试使用CASE WHEN ExpressionGroup By

SELECT user_id,
case when count(m_ticket.ticket_served_by)<2 then 'idle' 
     when count(m_ticket.ticket_served_by)=2 then 'Busy' 
     when count(m_ticket.ticket_served_by)>2 then 'Overload' end as status
FROM site_shift_schedule
LEFT JOIN m_shift_schedule ON site_shift_schedule.shift_id = m_shift_schedule.shift_id
left join m_ticket on site_shift_schedule.user_id=m_ticket.ticket_served_by
WHERE site_shift_schedule.shift_date =  '2019-02-11' and m_ticket.ticket_status in (4,5,6)
group by user_id