简体   繁体   English

分组在 DB2

[英]Group by in DB2

I have a query to fetch the nearest future doctor appointment for the users in DB2.我有一个查询要为 DB2 中的用户获取最近的未来医生预约。

  SELECT user_id, 
         appointment_id, 
         date 
    FROM (SELECT user_id, 
                 appointment_id, 
                 date 
            FROM doctors_appointment 
           WHERE date > current_timestamp 
             AND user_id 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.但是在 group by 语句中包含约会 ID 和日期会引发错误,这意味着它要求在 group by 中包含所有 select 字段。

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.如果给定用户在同一天有两个约会,它将为给定用户生成两行。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM