在SQL中使用GROUP时如何过滤数据

时间:2017-06-26 09:09:12

标签: sql

我得到了这个SQL语句:

SELECT t.*
FROM (SELECT * 
      FROM    accelerator_clinic_patient_status 
      ORDER BY status_id DESC) t 
INNER JOIN accelerator_clinic_campaign_patient_signup signup 
ON    (signup.patient_id = t.patient_id)
INNER JOIN accelerator_clinic_campaign campaign 
ON    (signup.campaign_id = campaign.campaign_id 
       AND campaign.clinic_user_id = 4978)
GROUP BY t.patient_id

代码找出表“accelerator_clinic_patient_status”中的最新状态

它包含的posts_id列是foregin-key,每个patient_id可以包含多个状态。

data example here

但是我感兴趣的是获取最新状态为“已预订”的患者ID列表 - 我想在执行select语句时过滤掉列表中的未预订(例如在发布的图像中) ,数据不应显示在查询中,因为最新状态为未预订)。代码现在返回一个具有最新状态的列表。

知道怎么做吗?

1 个答案:

答案 0 :(得分:0)

试试这个, 请在语法上改进以下代码,

select *,Rank() over (partiton by X.Patient_Id order by X.date_added desc) as Rankk from (SELECT t.*
FROM (SELECT * 
      FROM    accelerator_clinic_patient_status 
      ORDER BY status_id DESC) t 
INNER JOIN accelerator_clinic_campaign_patient_signup signup 
ON    (signup.patient_id = t.patient_id)
INNER JOIN accelerator_clinic_campaign campaign 
ON    (signup.campaign_id = campaign.campaign_id 
       AND campaign.clinic_user_id = 4978)
GROUP BY t.patient_id) as X where Rankk=1 and Status = 'Booked'

在Mysql中,像这样,

SET @rank=0;
SELECT @rank:=@rank+1,* 
          FROM    (accelerator_clinic_patient_status 
          ORDER BY status_id DESC) t 
    INNER JOIN accelerator_clinic_campaign_patient_signup signup 
    ON    (signup.patient_id = t.patient_id)
    INNER JOIN accelerator_clinic_campaign campaign 
    ON    (signup.campaign_id = campaign.campaign_id 
           AND campaign.clinic_user_id = 4978)
    GROUP BY t.patient_id) X 
Group By Patient_Id Order By date_added Desc