开发者

problem with result order on distinct select query

开发者 https://www.devze.com 2023-04-03 02:05 出处:网络
i have a table like this id name dategroup_id 1n111 2n211 3n422 4n522 i want ton write a query to return the group_id without duplicate ordered by date ASC

i have a table like this

id name date   group_id  
 1  n1   1     1
 2  n2   1     1
 3  n4   2     2
 4  n5   2     2 

i want ton write a query to return the group_id without duplicate ordered by date ASC

$query = " SELECT DISTINCT group_id FROM table ORDER BY date ASC";

this query will return 2 , 1 but this query is just going to consider date of the first row of each group_id to order the results

like if i have table like this

id name price  开发者_StackOverflowdate   group_id  
 1  n1   2300    1     1
 2  n2   3000    3     1
 3  n4   4000    2     2
 4  n5   2000    2     2 

second row with with '1' as group_id has the biggest date so i should get 1,2 as result but query doesn't care about second row with the '1' group_id and still return 2,1 it only cares about the first row of each id for ordering the results

hopefully there is a easy way to solve this and i dont need to do something wird like putting everything in the 2d array and order that then deleting duplicates


Try this

select group_id,max(date) as SortDate
from table
group by group_id
order by SortDate


If I understand your problem, it sounds like you need to group by the date first.

SELECT group_id
FROM (
SELECT
    group_id,
    min(date) as min_date
FROM table
GROUP BY group_id
) as t
ORDER BY t.min_date;
0

精彩评论

暂无评论...
验证码 换一张
取 消