SQL选择按周分组的最高SUM

时间:2016-11-28 12:52:54

标签: sql sqlite group-by

我如何更改以下SQLite3查询以获取按周分组的最高总计的行:

SELECT 
strftime('%W', date(p.match_date, 'unixepoch', 'localtime')) AS week_number,
sum(red_cards + yellow_cards) AS cards, user_id
FROM user_records
GROUP BY week_number, user_id
ORDER BY week_number, cards DESC

以上查询返回以下结果:

week_number - cards - user_id
44            5       1
44            1       2
45            2       2
45            1       1

我试图仅显示每周的第一行:

week_number - cards - user_id
44            5       1
45            2       2

是否有一些技巧可以调整查询以删除不必要的额外行?

3 个答案:

答案 0 :(得分:0)

尝试使用NOT EXISTS()

SELECT s.* FROM ( 
    SELECT 
        strftime('%W', date(p.match_date, 'unixepoch', 'localtime')) AS week_number,
        sum(red_cards + yellow_cards) AS cards, user_id
    FROM user_records
    GROUP BY week_number, user_id) s
WHERE NOT EXISTS(SELECT 1 FROM user_records p
                 WHERE strftime('%W', date(p.match_date, 'unixepoch', 'localtime')) = s.week_number
                 GROUP BY p.user_id
                 HAVING SUM(red_cards + yellow_cards) > s.cards)

答案 1 :(得分:0)

首先,使用CTE。然后一个简单的JOINWHERE子句将执行:

WITH w as (
      SELECT strftime('%W', date(p.match_date, 'unixepoch', 'localtime')) AS week_number,
             SUM(red_cards + yellow_cards) AS cards, user_id
      FROM user_records
      GROUP BY week_number, user_id
     )
SELECT w.*
FROM w
WHERE w.cards = (SELECT MAX(w2.cards)
                 FROM w w2
                 WHERE w2.week_number = w.week_number
                )
ORDER BY week_number;

请注意,如果多行在给定周内具有相同的最大值,则会返回多行。

答案 2 :(得分:0)

在SQLite 3.7.11或更高版本中,您可以使用max()返回组中具有最高值的行:

SELECT week_number,
       max(cards) AS cards,
       user_id
FROM (SELECT strftime('%W', date(p.match_date, 'unixepoch', 'localtime')) AS week_number,
             sum(red_cards + yellow_cards) AS cards,
             user_id
      FROM user_records
      GROUP BY week_number, user_id)
GROUP BY week_number
ORDER BY week_number;