I want to get the first two items of each month for each person. The idea is if the item have the same date, it should return the largest amount instead. I am having trouble writing a simple logical condition for it.
This is a screenshot of the table:
table datasource
The code should look something like this
SELECT MONTH(date) as month, name, item (WHERE Top 3 MONTH(date))
FROM table
GROUP BY MONTH(date), name, item
The expected output should look something similar to this:
expected output
(Edits): I’m sorry this is not for SQL server which I mislead the question with the hashtag. I am using phpmyadmin for SQL querying. Sorry for the misunderstanding.
4
Answers
You can use analytical function as follows:
Use
ROW_NUMBER
:The faster way to write this:
When working with dates, you should always take the year into account, unless you explicitly want to combine data from multiple years into one row. Nothing in your question suggests that the ultimate goal is to combine data from different time periods. So I would suggest:
You could also explicitly limit the data to a single year.