0

My table has multiple records of n_no column, and when I GROUP BY, it returns me the first record of the group, how do I get the last record?

SELECT * FROM mytable WHERE category = 16 AND status = 1 AND datetime >= "2020-01-06 00:00:00" AND datetime <= "2020-01-06 23:59:59" GROUP BY n_no ORDER BY datetime DESC LIMIT 0,30

Thanks.

[Solved by doing]

SELECT * FROM mytable WHERE (SELECT MAX(datetime) from mytable GROUP BY n_no) AND category = 16 AND status = 1 AND datetime >= "2020-01-06 00:00:00" AND datetime <= "2020-01-06 23:59:59" GROUP BY n_no ORDER BY datetime DESC LIMIT 0,30
eyllanesc
  • 235,170
  • 19
  • 170
  • 241
hatched
  • 795
  • 2
  • 9
  • 34

3 Answers3

1

Assuming you are using MySQL 8+, then ROW_NUMBER() can work here:

WITH cte AS (
    SELECT *, ROW_NUMBER() OVER (PARTITION BY n_no ORDER BY datetime DESC) rn
    FROM mytable
    WHERE category = 16 AND status = 1 AND
          datetime >= '2020-01-06' AND datetime < '2020-01-07'
)

SELECT *
FROM cte
WHERE rn = 1;
Tim Biegeleisen
  • 502,043
  • 27
  • 286
  • 360
0

The idea of "GROUP BY" is to get categories. not to select a record.

SELECT DISTINCT n_no, datetime, category, status, etc 
FROM mytable 
WHERE category = 16 
AND status = 1 
AND datetime BETWEEN "2020-01-06 00:00:00" AND "2020-01-06 23:59:59" 
ORDER BY datetime DESC
LIMIT 1

in this way you get all records from each n_no with the last date

0

You can try something like below,

SELECT * FROM mytable WHERE pk_col in (SELECT max(pk_col) FROM mytable WHERE category = 16 AND status = 1 AND datetime >= "2020-01-06 00:00:00" AND datetime <= "2020-01-06 23:59:59" GROUP BY n_no ORDER BY datetime DESC LIMIT 0,30)

Here, replace pk_col with the primary column name of your table.

Please find a sample here.

Saurabh
  • 882
  • 1
  • 5
  • 16