簡體   English   中英

有聚合函數時如何獲得最大的時間?

[英]How to get greatest time when there is an aggregate function?

我有一張這樣的桌子:

// mytable
+----+------+-------+-------------+
| id | type | score |  unix_time  |
+----+------+-------+-------------+
| 1  | 1    | 5     | 1463508841  |  -- this (current output)
| 2  | 1    | 10    | 1463508842  |
| 3  | 2    | 5     | 1463508843  |  -- this (current output)
| 4  | 1    | 5     | 1463508844  |
| 5  | 2    | 15    | 1463508845  |  -- this (expected output)
| 6  | 1    | 10    | 1463508846  |  -- this (expected output)
+----+------+-------+-------------+

這是我的查詢:

SELECT SUM(score), unix_time
FROM mytable
WHERE 1
GROUP BY type

這是電流輸出:

+-------+-------------+
| score |  unix_time  |
+-------+-------------+
| 30    | 1463508841  |
| 20    | 1463508843  |
+-------+-------------+

如您所見,輸出包含第一行的unix_time 但是我正在嘗試選擇最好的一個。

因此,這里是預期的輸出:

+-------+-------------+
| score |  unix_time  |
+-------+-------------+
| 30    | 1463508846  |
| 20    | 1463508845  |
+-------+-------------+

我怎樣才能做到這一點?

獲取每種類型的最大時間和總計,然后join類型。

select tm.maxtime,tot.total
from (select max(unixtime) maxtime, type
     from mytable 
     group by type) tm
join (SELECT SUM(score) total, type
      FROM mytable
      GROUP BY type) tot
on tot.type = tm.type

或簡單地

select max(unixtime) maxtime, sum(score) total
from mytable 
group by type

我認為您需要求和(分數)和最大值(unix_time)作為分組值

SELECT type, SUM(score), max(unix_time)
FROM mytable
GROUP BY type

我省略了1,因為似乎沒有意義..

我想你只想要max()

SELECT SUM(score), MAX(unix_time)
FROM mytable
WHERE 1
GROUP BY type;

MySQL幾乎是唯一接受您的查詢版本的數據庫。 您應該得到一個錯誤,因為unix_time不在GROUP BY ,也不是聚合函數的參數。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM