简体   繁体   中英

How to order by before group by in MYSQL

My query doesn't work :(

These is are my queries :

SELECT * 
FROM PESAN 
GROUP BY ID_PENGIRIM 
ORDER BY TANGGAL_PESAN

SELECT ... min(date) 
FROM ... 
GROUP BY ... 
ORDER BY min(...)

So, what queries fit for what I need..

Thanks in advance

在此处输入图片说明

Your expected output implies that you want the most recent TANGGAL_PESAN record for each ID_PENGIRIM group. If so, then the following query should work:

SELECT p1.*
FROM PESAN p1
INNER JOIN
(
    SELECT ID_PENGIRIM, MAX(TANGGAL_PESAN) AS max_time
    FROM PESAN
    GROUP BY ID_PENGIRIM
) p2
    ON p1.ID_PENGIRIM = p2.ID_PENGIRIM AND
       p1.TANGGAL_PESAN = t2.max_time;

The subquery finds the latest TANGGAL_PESAN timestamp for each group. Then, we join the PESAN table to this subquery to retain only the latest records we want. As to why your attemtps were not working, you would need to use some sort of subquery to get the result you want.

You can partition by ID_PENGIRIM sort the partition by TANGGAL_PESAN , give rank and filter results where rank is 1

select * from (
  select 
  p.*,
  row_number() over (partition by  id_pengirim order by tanggal_pesan desc nulls last) as rank 
  from pesan p
) where rank = 1

results

| ID_PESAN | ID_ANGGOTA | ID_PENGIRIM | ISI_PESAN |         TANGGAL_PESAN | RANK |
|----------|------------|-------------|-----------|-----------------------|------|
|        1 |          1 |           1 |         a | 2017-12-29 07:32:52.0 |    1 |
|        4 |          1 |           2 |         d | 2017-12-28 07:32:52.0 |    1 |

ddl

create table PESAN (
  id_pesan varchar2(15),
  id_anggota varchar2(15),
  id_pengirim varchar2(15),
  isi_pesan varchar2(15),
  tanggal_pesan timestamp
);

dml

insert into PESAN values ('1','1','1','a',sysdate-1);
insert into PESAN values ('2','1','2','b',sysdate-4);
insert into PESAN values ('3','1','1','c',sysdate-3);
insert into PESAN values ('4','1','2','d',sysdate-2);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM