计算多个日期的最大值数

时间:2013-04-10 08:56:02

标签: mysql sql count

对于给定的用户,我想创建一个SQL查询,返回用户每天获得最佳值的时间。
我使用MySQL。

-----------------------------
| User |    Date    | Value |
-----------------------------
| John | 2013-04-03 | 57    |
| John | 2013-04-04 | 13    |
| John | 2013-04-05 | 102   |
| John | 2013-04-06 | 64    |
| Bob  | 2013-04-03 | 8     |
| Bob  | 2013-04-04 | 83    |
| Bob  | 2013-04-05 | 44    |
| Bob  | 2013-04-06 | 101   |
| Paul | 2013-04-03 | 22    |
| Paul | 2013-04-04 | 72    |
| Paul | 2013-04-05 | 50    |
| Paul | 2013-04-06 | 15    |
-----------------------------

示例:
约翰:2次(2013-04-03& 2013-04-05)
鲍勃:2次(2013-04-04& 2013-04-06)
保罗:0次

我不知道我必须使用哪些功能( COUNT(*) SUM(*) MAX(Value) GROUP BY ?) 如何为每个日期创建循环并进行总结?

3 个答案:

答案 0 :(得分:0)

由于您尚未提及您正在使用的RDBMS,因此这是一个可以在几乎所有 RDBMS上运行的查询:

SELECT  aa.User, COUNT(bb.User ) TotalCount
FROM    (SELECT DISTINCT User FROM TableName) aa
        LEFT JOIN
        (
            SELECT  a.User
            FROM    TableName a
                    INNER JOIN
                    (
                        SELECT  Date, MAX(Value) max_val
                        FROM    TableName
                        GROUP   BY Date
                    ) b ON  a.Date = b.Date AND
                            a.Value = b.max_val
        ) bb ON aa.User = bb.User 
GROUP   BY aa.User

输出

╔══════╦════════════╗
║ USER ║ TOTALCOUNT ║
╠══════╬════════════╣
║ Bob  ║          2 ║
║ John ║          2 ║
║ Paul ║          0 ║
╚══════╩════════════╝

答案 1 :(得分:0)

您可以尝试以下查询来实现此目的 -

WITH T AS (SELECT USER,COUNT(*) 
             FROM TABLE_NAME WHERE (DATE,VALUE) IN (SELECT DATE, MAX(VALUE) 
                                                      FROM TABLE_NAME 
                                                  GROUP BY DATE)
          GROUP BY USER)

SELECT * FROM T 
UNION SELECT USER,0 
        FROM TABLE_NAME 
       WHERE USER NOT IN (SELECT USER FROM T)

答案 2 :(得分:0)

我想出了以下

  select
   u.user, count(*) as top_performer
  from 
    my_table u
    join (
      select valdate, max(value) as value 
      from my_table 
      group by valdate
    ) mv on
      mv.valdate = u.valdate and
      mv.value = u.value
  group by
    u.user

JW的回答可能更完整,因为它列出了Paul的Zero得分 - 另一方面,我的回答是假设您left join到另一个用户表。

http://sqlfiddle.com/#!2/409ca/11