具有案例的复杂查询分组

时间:2013-12-02 13:34:39

标签: mysql sql group-by

我有一张桌子:

Visit (FromId, ToId, VisitTime)

其中FromId和ToId是FK到表

UserProfile (uid, name, age ...)

作为具有我的UID的用户,我想要选择我访问过的所有个人资料,或者在访问时间点排序的一个结果集中访问我的所有个人资料以及“访问方向”的指示。

我使用此选择获取数据:

SELECT  CASE WHEN a.FromID = 'yourIDHere' 
            THEN c.Name
            ELSE b.Name
    END Name,
    CASE WHEN a.FromID = 'yourIDHere' 
            THEN c.Age
            ELSE b.Age
    END Age,
    a.VisitTime,
    CASE WHEN a.FromID = 'yourIDHere' 
            THEN 'You'
            ELSE 'Friend'
    END DirectionOfVisit
FROM    Visit a
    INNER JOIN UserProfile b
        ON a.FromID = b.Uid
    INNER JOIN UserProfile c
        ON a.ToID = c.Uid
WHERE   'yourIDHere' IN (a.FromID, a.ToID)
ORDER   BY a.VisitTime

现在打印(伪输出)

Jack (id1) | IN |12.12.2012
Jack (id1) | IN |11.12.2012
Jack (id1) | IN |11.12.2012
Jack (id1) | OUT | 13.12.2012
Jack (id1) | OUT | 12.12.2012
Michael (id5) | IN | 5.12.2012
Michael (id5) | OUT | 6.12.2012
Michael (id5) | OUT | 5.12.2012

我希望列表是这样的:

Jack | IN | 12.12.2012 (the most recent)
Jack | OUT | 13.12.2012 (the most recent)
Michael (id5) | IN | 5.12.2012 (the most recent)
Michael (id5) | OUT | 6.12.2012 (the most recent)

我知道GROUP命令会解决它但对我来说太复杂了(初学者)。

1 个答案:

答案 0 :(得分:2)

您可以使用GROUP BY和聚合函数来获取结果。由于您需要每个nametype(IN / OUT)的最新日期,因此您可以在日期列中使用max()聚合函数。然后,您将在要返回的其他列上使用GROUP BY:

基本语法为:

select
  name,
  type,
  max(date) date
from yourtable
group by name, type;

请参阅SQL Fiddle with Demo

如果要使用现有查询返回最大日期,只需展开要使用的查询:

select name, age, max(VisitTime), DirectionOfVisit
from
(
    SELECT  CASE WHEN a.FromID = 'yourIDHere' 
                THEN c.Name
                ELSE b.Name
        END Name,
        CASE WHEN a.FromID = 'yourIDHere' 
                THEN c.Age
                ELSE b.Age
        END Age,
        a.VisitTime,
        CASE WHEN a.FromID = 'yourIDHere' 
                THEN 'You'
                ELSE 'Friend'
        END DirectionOfVisit
    FROM    Visit a
        INNER JOIN UserProfile b
            ON a.FromID = b.Uid
        INNER JOIN UserProfile c
            ON a.ToID = c.Uid
    WHERE   'yourIDHere' IN (a.FromID, a.ToID)
) d
group by name, age, DirectionOfVisit;

请参阅SQL Fiddle with Demo