SQL:为每个组

时间:2016-01-17 23:30:04

标签: mysql sql database ms-access

让我们说我有一个表(MS-ACCESS / MYSQL)有两列(Time' hh:mm:ss',Value),我希望得到每组行的最常值

例如我有

Time    | Value
4:35:49 | 122
4:35:49 | 122
4:35:50 | 121
4:35:50 | 121
4:35:50 | 111
4:35:51 | 122
4:35:51 | 111
4:35:51 | 111
4:35:51 | 132
4:35:51 | 132

我希望每次获得最频繁的价值

Time    | Value
4:35:49 | 122
4:35:50 | 121
4:35:51 | 132

提前致谢

备注 我需要得到与此Excel solution : Get the most frequent value for each group

相同的结果

**我的SQL解决方案**

我发现了一个解决方案(Source)可以正常使用mysql,但我无法在ms-access中使用它:

select cnt1.`Time`,MAX(cnt1.`Value`)
from (select COUNT(*) as total, `Time`,`Value`
from `my_table`
group by `Time`,`Value`) cnt1,
(select MAX(total) as maxtotal from (select COUNT(*) as total, 
`Time`,`Value` from `my_table` group by `Time`,`Value`) cnt3 ) cnt2
where cnt1.total = cnt2.maxtotal GROUP BY cnt1.`Time`

2 个答案:

答案 0 :(得分:2)

考虑使INNER JOIN匹配两个派生表子查询,而不是与WHERE子句匹配的子查询select语句列表。这已经在MS Access中进行了测试:

SELECT MaxCountSub.`Time`, CountSub.`Value`    
FROM    
     (SELECT myTable.`Time`, myTable.`Value`, Count(myTable.`Value`) AS CountOfValue
      FROM myTable
      GROUP BY myTable.`Time`, myTable.`Value`) As CountSub

INNER JOIN 

     (SELECT dT.`Time`, Max(CountOfValue) As MaxCountOfValue
      FROM
           (SELECT myTable.`Time`, myTable.`Value`, Count(myTable.`Value`) AS CountOfValue
            FROM myTable
            GROUP BY myTable.`Time`, myTable.`Value`) As dT
      GROUP BY dT.`Time`) As MaxCountSub

ON CountSub.`Time` = MaxCountSub.`Time` 
AND CountSub.CountOfValue = MaxCountSub.MaxCountOfValue

答案 1 :(得分:1)

您可以通过以下查询执行此操作:

select time, value 
from (select value, time from your_table 
group by value , time
order by count(time) desc
) temp where temp.value = value
group by value