2017-02-27 171 views
0

我的表結構如下的Mysql按日期排序和group by結果不同

id parent last_date  sub_type 
---------------------------------- 
11 9  2017-02-28 1101 
10 9  2016-08-26 1101 
8 1  2017-02-20 1101 
12 12  2016-08-31 1102  
14 12  2016-12-20 1102  
9 9  2016-12-31 1101 
13 12  2017-03-23 1102 
2 1  2017-01-25 1101 
1 1  2016-12-31 1101 

我想基於日期(最長的第一)各sub_type讀取行。我想下面的查詢

SELECT * FROM mytable GROUP BY sub_type ORDER BY ISNULL(last_date) DESC, last_date DESC 

並且它導致

id parent last_date sub_type  
-------------------------------- 
1 1  2016-12-31 1101  
12 12  2016-08-31 1102  

但我希望下面的結果。

id parent last_date sub_type  
-------------------------------- 
13 12  2017-03-23 1102 
11 9  2017-02-28 1101  

請指導我以取得以上結果。

編輯:

LAST_DATE可能有NULL值將超過日最大項的優先級。這就是爲什麼我選擇ISNULL DESC命令。

+1

'SELECT sub_type,MAX(last_date)FROM mytable GROUP BY sub_type'? –

+0

'id'主鍵? –

+1

如果存在多個空記錄會怎麼樣?您想要獲取哪張唱片? – Blank

回答

1

您可以在WHERE子句中使用ORDER BY和LIMIT 1中的相關子查詢來查找您正在查找的行的ID。

SELECT * 
FROM mytable t1 
WHERE id = (
    SELECT id 
    FROM mytable t2 
    WHERE t2.sub_type = t1.sub_type 
    ORDER BY ISNULL(last_date) DESC, last_date DESC, id DESC 
    LIMIT 1 
) 

演示:http://rextester.com/DSPH11524

注:sub_type應該被索引。

+0

非常感謝您的回答。我會嘗試你的建議 – ArK

1

這是一個典型的問題,通過聚合獲取每個組中的一條記錄。試試這個:

select 
    mytable.* 
from mytable 
join (
    select max(last_date) as last_date, sub_type from mytable group by sub_type 
) t1 on mytable.sub_type = t1.sub_type and mytable.last_date = t1.last_date 

看到這篇文章How to select the first/least/max row per group in SQL

相關鏈接右:

Retrieving the last record in each group

and demo in sqlfiddle。

編輯:

如果沒有2相同的最後日期和空優先級,那麼試試這個:

select 
    mytable.* 
from mytable 
join (
    select 
     max(last_date) as last_date, 
     max(isnull(last_date)) nulled, 
     sub_type 
    from mytable 
    group by sub_type 
) t1 on mytable.sub_type = t1.sub_type 
and (t1.nulled and mytable.last_date is null or (t1.nulled <> 1 and mytable.last_date = t1.last_date)) 

demo在sqlfiddle。

+0

非常感謝答案。我會嘗試你的建議。 – ArK

1

您也可以通過根據sub_type列和last_date列的降序給出行號來完成此操作。

查詢

select t1.`id`, t1.`parent`, t1.`last_date`, t1.`sub_type` from 
(
    select `id`, `parent`, `last_date`, `sub_type`, 
    (
     case `sub_type` when @A 
     then @R := @R + 1 
     else @R := 1 and @A := `sub_type` end 
    ) as `rn` 
    from `your_table_name` t, 
    (select @R := 0, @A := '') r 
    order by `sub_type`, `last_date` desc 
)t1 
where t1.`rn` = 1; 

Sql Fiddle demo

+0

感謝您的回答。我會嘗試你的建議 – ArK

0

你已經寫了錯誤的查詢。

指定where條件後的條件where條款

以下查詢會給出您的預期結果。

SELECT id,parent,max(last_Date),sub_type FROM mytable GROUP BY sub_type 
+0

@Ajay Singh感謝你的提示。它的類型錯誤。現在更正 – ArK

+0

'id'和'parent'列沒有聚合函數,也沒有在group by子句中。 – Wanderer

+0

@ullas在mysql中沒有必要指定group by的所有列,它將按組表達式 –