mysql查询从表中获取max和distinct值

时间:2015-08-10 12:46:35

标签: php mysql

这是我的原始表

+--------+-----------------------+
|cTotal  |         dateT         | 
+--------+-----------------------+
| 4      |  2015-07-21 22:41:03  | 
| 7      |  2015-08-21 01:21:12  | 
| 10     |  2015-08-21 04:35:06  | 
| 16     |  2015-09-21 12:20:05  | 
| 23     |  2015-09-21 16:51:24  | 
| 48     |  2015-10-21 02:11:08  | 
+--------+-----------------------+

我使用STR_TO_DATE并获取

+--------+--------------+
|cTotal  |    dateT     | 
+--------+--------------+
| 4      |  2015-07-21  | 
| 7      |  2015-08-21  | 
| 10     |  2015-08-21  | 
| 16     |  2015-09-21  | 
| 23     |  2015-09-21  | 
| 48     |  2015-10-21  | 
+--------+--------------+

但我希望每个不同日期的cTotal的最大值,如下所示:

+--------+--------------+
|cTotal  |    dateT     | 
+--------+--------------+
| 4      |  2015-07-21  | 
| 10     |  2015-08-21  | 
| 23     |  2015-09-21  | 
| 48     |  2015-10-21  | 
+--------+--------------+

但我没有得到我想要的结果。

SELECT  STR_TO_DATE( `dateT` , '%Y-%m-%d' ) AS `dateL`, `cTotal` 
FROM `pstable` 
INNER JOIN (
SELECT STR_TO_DATE( `dateT , '%Y-%m-%d' ) AS `dateL1` , MAX( `cTotal` ) AS `MaxCDay`
FROM `pstable`
GROUP BY `dateLikes`
) `grouped` 
ON `pstable`.`dateL` = `grouped`.`dateL1`
AND `pstable`.`cTotal` = `grouped`.`MaxCDay`

3 个答案:

答案 0 :(得分:3)

SELECT date(dateT) as theDate, max(cTotal) as cTotal
FROM myTable 
GROUP BY date(dateT)
ORDER BY cTotal

答案 1 :(得分:1)

 select max(cTotal), DATE(dateT) from table_name group by DATE(dateT)  

答案 2 :(得分:1)

您可以在原始表格上执行此操作:

select max(cTotal), dateT from table1
   group by str_to_date(dateT,'%Y-%m-%d');

请在此处查看SQLFiddle演示。