2016-01-17 46 views
0

假設我有一個包含兩列(Time'hh:mm:ss',Value)的表(MS-ACCESS/MYSQL),我想獲得最常見的值爲每一組行。SQL:獲取每個組的最頻繁值

,比如我有

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

** MY SQL解決方案**

我找到了解決方案(Source)與MySQL的工作正常,但我不能讓它在運行MS-訪問:

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` 
+0

小組如何確定?同一時間值? – Parfait

+0

是的每個組都有一個特定的時間值 – Horthe92

+0

你做了什麼做得很遠? – Shadow

回答

0

你可以這樣做通過這樣的查詢:

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 
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 
相關問題