MySQL:查询过滤列后获取MAX值

时间:2014-02-11 01:25:11

标签: mysql sorting max

我有下表

+------------+-------+------------+-----------+
| date       | time  | custom_id  | Number    |
+------------+-------+------------+-----------+
| 01/02/2014 | 01:00 | ABC123     | 15        |
| 01/06/2014 | 02:00 | ABC123     | 11        |
| 01/06/2014 | 00:00 | ABC123     | 17        |
| 01/06/2014 | 01:00 | HEY567     | 28        |
| 01/07/2014 | 01:00 | ABC123     | 17        |
| 01/08/2014 | 00:00 | HEY567     | 28        |
| 01/09/2014 | 14:00 | ABC123     | 17        |
| 01/10/2014 | 22:00 | HEY567     | 28        |
| 01/10/2014 | 23:00 | ABC123     | 17        |
| 01/12/2014 | 18:30 | HEY567     | 28        |
+------------+-------+------------+-----------+

我怎么能:

  1. 选择 01/06/2014 的日期范围从时间 00:00开始 UNTIL 01/10 / 2014 23:00

  2. MAX 订购 MIN 每天名为数字的列

  3. 同时根据 custom_id 列对表格进行排序

  4. 我希望它最终看起来与此相似:

    +------------+-------+------------+-----------+
    | date       | time  | custom_id  | Number    |
    +------------+-------+------------+-----------+
    | 01/06/2014 | 01:00 | HEY567     | 28        |
    | 01/06/2014 | 00:00 | ABC123     | 17        |
    | 01/06/2014 | 02:00 | ABC123     | 11        |
    | 01/07/2014 | 01:00 | ABC123     | 17        |
    | 01/08/2014 | 00:00 | HEY567     | 28        |
    | 01/09/2014 | 14:00 | ABC123     | 17        |
    | 01/10/2014 | 22:00 | HEY567     | 28        |
    | 01/10/2014 | 23:00 | ABC123     | 17        |
    +------------+-------+------------+-----------+
    

    如何使用MySQL查询完成此操作?

    提前致谢

    SQLFiddle我之前做过的查询:http://sqlfiddle.com/#!2/3d2b9/1

2 个答案:

答案 0 :(得分:1)

这是一个MySQL查询,它将查找2014年1月6日到2014年1月10日之间的日期,然后按数字列降序排列,custom_id按升序排序

SELECT date, MIN(time) as time, custom_id, SUM(Number) as numbersum
FROM traffic
WHERE time between "00:00" and "23:00" and date between "01/06/2014" and "01/10/2014"
GROUP BY date, custom_id, HOUR(time)
ORDER BY numbersum desc, custom_id

答案 1 :(得分:1)

我不确定您的专栏'时间'是否包含'23:30'这样的数据,这可能会有效:

SELECT date, time, custom_id, Number
FROM traffic
WHERE CONCAT(date, " ", time) BETWEEN "01/06/2014 00:00" AND "01/10/2014 23:00"
ORDER BY date, CAST(Number as SIGNED) DESC, custom_id

CONCAT组合'日期'和'时间'。

http://sqlfiddle.com/#!2/f57b7/8