使用其他条件计算分组查询中的记录

时间:2009-04-28 17:40:27

标签: sql mysql

我有一份包含以下相关字段的报告表:

user_id (int 11)
submitted_date (datetime)
approved_flag (shortint 1)

user_id行有多行,有些行approved_flag = 0,有些行approved_flag = 1,每行都有唯一的submitted_date

我需要计算已批准和未批准的报告。但我只想计算每个用户最近提交的报告(最近的submitted_date),而不管approved_flag

所以,如果有4条这样的记录:

    user_id, submitted_date, approved_flag
    1, 2009-04-01 01:00, 1
    1, 2009-04-01 02:00, 0
    1, 2009-04-01 03:00, 1 (using this record)
    2, 2009-04-02 01:00, 1 (using this record)
如果我们有

,则该计数将获得2个批准且未经批准
    user_id, submitted_date, approved_flag
    1, 2009-04-01 01:00, 1
    1, 2009-04-01 02:00, 0
    1, 2009-04-01 03:00, 0 (using this record)
    2, 2009-04-02 01:00, 0
    2, 2009-04-02 02:00, 1 (using this record)

计数将被批准1(用户ID 2)和1未批准(用户ID 1)。

再次总结一下,因为它不容易描述:我想要表中唯一用户的总数(无论每个用户的#行数),我希望它分解为“已批准”和“未批准” '基于每个用户最新报告的approved_flag

非常感谢任何帮助,谢谢!

3 个答案:

答案 0 :(得分:1)

SELECT approved_flag, COUNT(*)
FROM 
  Table t
  INNER JOIN (
    SELECT user_id, submitted_date = MAX(submitted_date)
    FROM Table
    GROUP BY user_id
  ) latest ON latest.user_id = t.user_id
              AND latest.submitted_date = t.submitted_date
GROUP BY approved_flag

答案 1 :(得分:1)

可以想到两种方法来做到这一点。第一个可能是最易读的,搜索每个用户的最后submit_date,然后显示该时间戳的批准:

select a.user_id, a.submitted_date, a.approved_flag
from approvals a
inner join (
    select user_id, maxdt = max(submitted_date)
    from approvals
    group by user_id
) latest on latest.user_id = a.user_id 
    and latest.maxdt = a.submitted_date

第二种方法是将表连接到同一用户的未来行,并在where子句中指定这些行不存在。这为您提供了每个用户的最新条目:

select cur.user_id, cur.submitted_date, cur.approved_flag
from approvals cur
left join approvals next
    on next.user_id = cur.user_id
    and next.submitted_date > cur.submitted_date
where next.user_id is null

答案 2 :(得分:0)

SELECT user_id, approved_flag, COUNT(*)
FROM reports 
WHERE NOW() - submitted_date < 'whatever'
GROUP BY user_id, approved_flag 

希望它有效..