2016-01-24 66 views
0

我正在面對MySQL查詢中的一個問題,它是「具有最大值的行的標識」的變體。對於我的所有試驗,我要麼得到錯誤或者結果不正確。行中的MySQL最大值

這裏是表結構

Row_id 
Group_id 
Grp_col1 
Grp_col2 
Field_for_aggregate_func 
Another_field_for_row 

與特定GROUP_ID所有行,我想通過域組Grp_col1,Grp_col2然後得到Field_for_aggregate_func的最大值,然後相應Another_field_for_row的價值。

查詢我試圖像下面

SELECT c.* 
FROM mytable as c left outer join mytable as c1 
on (
    c.group_id=c1.group_id and 
    c.Grp_col1 = c1.Grp_col1 and 
    c.Grp_col2 = c1.Grp_col2 and 
    c.Field_for_aggregate_func > c1.Field_for_aggregate_func 
) 
where c.group_id=2 

在這個問題的替代解決方案我想,因爲這一個高性能的解決方案將用於大型數據集。

編輯:這裏是行的樣本集和預期的答案

Group_ID Grp_col1 Grp_col2 Field_for_aggregate_func Another_field_for_row 
2   --  N  12/31/2015    35 
2   --  N  1/31/2016    15 select 15 from group for max value 1/31/2016 

2   --  Y  12/31/2015    5 
2   --  Y  1/1/2016     15 
2   --  Y  1/2/2016     25 
2   --  Y  1/3/2016     30 select 30 from group for max value 1/3/2016 
+1

您能想象如果您提供樣本數據和預期結果,獲得解決方案的速度會更快嗎?你知道什麼樣的數據,你知道結果應該是什麼樣的--->我們不 –

+0

這是一個次要問題,除非我有超過1個解決方案。現在我沒有得到任何查詢工作。一旦我有多個解決方案,我將使用快速解決方案,除非沒有其他選擇,否則任何延遲都必須容忍。理想情況下,我想用查詢解決它,當沒有任何工作時,我會將整個結果集放到我的PHP程序中,然後在那裏解決。 – bvnbhati

+0

所以在輸出中,你想要15和30? – Utsav

回答

1

您可以使用一個子查詢找到了最大值,再加入與原表,沿着線:

select m1.group_id, m1.grp_col1, m1.grp_col2, m1.another_field_for_row, max_value 
from mytable m1, (
    select group_id, grp_col1, grp_col2, max(field_for_aggregate_func) as max_value 
    from mytable 
    group by group_id, grp_col1, grp_col2) as m2 
where m1.group_id=m2.group_id 
    and m1.grp_col1=m2.grp_col1 
    and m1.grp_col2=m2.grp_col2 
    and m1.field_for_aggregate_func=m2.max_value; 

注意給定分組有多個max_value。您將獲得該分組的多行。 Fiddle here.

+0

這不是我想要的。我想從每個組中具有最大值'field_for_aggregate_func'的行開始'another_field_for_row'。 'another_field_for_row'不是要分組的列的一部分。我在我的問題中已經明確提到它。 – bvnbhati

+0

你能舉幾個樣本行的輸入和結果數據來說明嗎?如上所述,您可以將another_field放在分組外(但可能有最大值重複)。我編輯了答案以使其更清楚,但請提供一些示例數據。 – wwkudu

+0

'another_field_for_row'對於每個組都是唯一的,因爲我通過應用程序代碼將unique_field_for_row作爲唯一鍵的一部分來實現(因爲MySQL不檢查唯一鍵約束) – bvnbhati

0

試試這個。這裏

http://sqlfiddle.com/#!9/9a3c26/8

Select t1.* from table1 t1 inner join 
(
Select a.group_id,a.grp_col2, 
A.Field_for_aggregate_func, 
count(*) as rnum from table1 a 
Inner join table1 b 
On a.group_id=b.group_id 
And a.grp_col2=b.grp_col2 
And a.Field_for_aggregate_func 
<=b.Field_for_aggregate_func 
Group by a.group_id, 
a.grp_col2, 
a.Field_for_aggregate_func) t2 
On t1.group_id=t2.group_id 
And t1.grp_col2=t2.grp_col2 
And t1.Field_for_aggregate_func 
=t2.Field_for_aggregate_func 
And t2.rnum=1 

這裏

見小提琴演示第一,我分配在降基於日期順序ROWNUMBER。選擇該日期的所有記錄。