一个GROUP BY语句下的不同聚合函数

时间:2014-10-03 05:54:21

标签: sql join group-by aggregate-functions

我有以下表格:

主题:

topicID(PK), 用户ID(FK), 标题, dateCreated会

消息:

MESSAGEID(PK), topicID(FK), 用户ID(FK), 邮件正文, dateCreated会

用户:

用户ID(PK), 用户名


我想选择最后一条消息的用户名,发布最后一条消息的日期以及主题中的消息数量等。

我无法选择上次发布消息的用户名。到目前为止,我提出的最佳查询仅选择上次发布消息的最后日期,而不是用户名。我应该在查询中添加什么内容?

SELECT Topics.title, Users.username, Topics.dateCreated, COUNT(Messages.messageID) as postsCount, MAX(Messages.datePosted) as lastPostedDate
    FROM Topics 
    JOIN Users ON Topics.userID = Users.userID 
    JOIN Messages ON Topics.topicID = Messages.topicID 
    GROUP BY Topics.topicID

2 个答案:

答案 0 :(得分:1)

并不完全确定您的希望,但这可能会有所帮助:

SELECT
      Topics.title
    , tuser.username            AS TopicUserName
    , MIN(Topics.dateCreated)   AS TopicDate
    , muser.username            AS MessageUserName
    , COUNT(Messages.messageID) AS postsCount
    , MIN(Messages.datePosted)  AS firstPostedDate
    , MAX(Messages.datePosted)  AS lastPostedDate
FROM Messages
      JOIN Users muser
                  ON Messages.userID = Users.userID
      JOIN Topics
                  ON Topics.topicID = Messages.topicID
      JOIN Users tuser
                  ON Topics.userID = Users.userID
GROUP BY
      Topics.title
    , tuser.username
    , muser.username
ORDER BY
      lastPostedDate DESC
LIMIT 0,1
;

答案 1 :(得分:0)

解决方案是:

SELECT 
Topics.title
, Users.username
, Topics.dateCreated
, COUNT(Messages.messageID) as postsCount
, lastPost.lastPostUser
, lastPost.lastPostDate  
FROM Topics 
JOIN (
    SELECT 
    Max(Messages.datePosted) as lastPostDate
    , Users.username as lastPostUser
    , Users.userID FROM Topics
    JOIN Users ON Topics.userID = Users.userID 
    JOIN Messages ON Topics.topicID = Messages.topicID 
    GROUP BY Topics.topicID) lastPost
ON Topics.userID = lastPost.userID
JOIN Users ON Topics.userID = Users.userID 
JOIN Messages ON Topics.topicID = Messages.topicID 
GROUP BY Topics.topicID;

编写此类查询的一种好方法是将其细分为几个简单的查询,并在最后合并它们。在我的情况下

SELECT 
Max(Messages.datePosted) as lastPostDate
, Users.username as lastPostUser
, Users.userID FROM Topics
JOIN Users ON Topics.userID = Users.userID 
JOIN Messages ON Topics.topicID = Messages.topicID 
GROUP BY Topics.topicID;

刚加入:

SELECT 
    Topics.title
    , Users.username
    , Topics.dateCreated
    , COUNT(Messages.messageID) as postsCount
    FROM Topics         
    JOIN Users ON Topics.userID = Users.userID 
    JOIN Messages ON Topics.topicID = Messages.topicID 
    GROUP BY Topics.topicID;