开发者

Group by in DB2

开发者 https://www.devze.com 2023-03-19 17:08 出处:网络
I have a query to fetch the nearest future doctor appointment for the users in DB2. SELECT user_id, appointment_id,

I have a query to fetch the nearest future doctor appointment for the users in DB2.

  SELECT user_id, 
         appointment_id, 
         date 
    FROM (SELECT user_id, 
                 appointment_id, 
                 date 
            FROM doctors_appointment 
           WHERE date > current_timestamp 
             AND user_i开发者_运维问答d IN (23, 24, 25)
        ORDER BY date ASC ) as tmp_appointment 
GROUP BY user_id

But It throws error to include appointment_id and date in group by statement which means it asks to include all select fields in group by.

If I include all fields in group by the result will be like this:

   user_id    appointment_id      date 
   --------  ----------------     -------
    23            450             2011-07-20
    23            451             2011-07-26
    25            452             2011-07-18

But I need the result like below:

   user_id    appointment_id      date 
   --------   --------------       -------
    23            450             2011-07-20
    25            452             2011-07-18


I think this does the trick:

  SELECT D.User_ID, D.Appointment_ID, D.Date 
    FROM Doctors_Appointment AS D
    JOIN (SELECT User_ID, MIN(Date) AS Apt_Date
            FROM Doctors_Appointment 
           WHERE Date > current_timestamp 
             AND User_ID IN (23, 24, 25)
           GROUP BY User_ID) AS T 
      ON T.User_ID = D.User_ID AND T.Apt_Date = D.Date;

It would produce two rows for a given user if said user has two appointments on the same day.

0

精彩评论

暂无评论...
验证码 换一张
取 消