Click here to Skip to main content
15,889,808 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Howdy,

I'm new here and hope that someone can help me with my issue.
I have a toplist which shows unique lakes (mm) for each user (mycall) in a table that also tracks confirmed lakes (conf = 1). Grouping by mycall and ordering by total gives me the toplist.
Now for my problem. I need the list to also be sorted by the time. The table has a datetime column (tid). I need the date for the latest unique count.

Example table
mycall ,tid, mm, conf
SM6ABC, 2022-04-01 09:00:00, AAAA, 1
SM6ABC, 2022-04-01 09:01:00, AAAB, 1
SM6ABC, 2022-04-01 09:12:00, AAAA, 1
SM6CBA, 2022-04-01 09:10:00, BBBB, 1
SM6CBA, 2022-04-01 09:11:00, AAAA, 1
SM6AAA, 2022-04-01 09:12:00, AAAA, 1


Output should be
SM6ABC, 2 (Last unique data is SM6ABC, 20220401 09:01:00, AAAB, 1)
SM6CBA, 2 (Last unique data is SM6CBA, 2022-04-01 09:11:00, AAAA, 1)
SM6AAA, 1


What I have tried:

MySQL
SQL
SELECT mycall, COUNT(DISTINCT mm) AS 'total' FROM KJ_log WHERE mm !='' AND conf = '1' GROUP BY mycall ORDER BY total DESC
This works fine but how do I include the datetime sorting? I tried to add select MAX(tid) but that returns last date for the user.
Posted
Updated 21-Apr-22 9:24am
v4

1 solution

You can add several fields/columns into ORDER BY clause:
SQL
ORDER BY <Field1> [SortOrder1], <Field2> [SortOrder2]

See: MySQL ORDER BY[^]

If you wan to include last date, try this:
SQL
SELECT mycall, MAX(tid) AS 'tid', COUNT(DISTINCT mm) AS 'total'
FROM KJ_log
WHERE mm !='' AND conf = '1'
GROUP BY mycall
ORDER BY total DESC


An alternative way is to use window functions: MySQL :: MySQL 8.0 Reference Manual :: 12.21 Window Functions[^]
MySQL Window Functions: An Essential Guide to Window Functions in MySQL[^]

[EDIT]
Your tid column contains incorrect data type / format!
See this demo: MySQL 8.0 | db<>fiddle[^]
 
Share this answer
 
v2
Comments
SM6TOB 21-Apr-22 14:29pm    
Unfortunately your solution returns thw wrong answer :( I have also tried the MAX(tid) but then the date of (SM6ABC, 20220401 09:12:00, AAAA, 1) will be used. Look at output above.

Abt Window functions - never heared of but will hav a look at that too!
Maciej Los 21-Apr-22 15:07pm    
See updated answer.
SM6TOB 21-Apr-22 15:25pm    
tid corrected
Maciej Los 21-Apr-22 15:40pm    
And...
SM6TOB 22-Apr-22 1:39am    
You reply "And...", I say and what???
Problem still remains!
Have a look at my output above. You will not get that with your MAX(tid) solution.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900