How to Get and Sort Counts per Value in SQL
The aim of this pageš is to explain how to sort counts of a certain value in descending order based on the particular example of a SQL query. In my case, I am writing a self-review and I was curious how many tickets I handled. I have a data set containing all tickets for last year (no need to filter to give year) with many fields. I am only interested in what the counts for tickets with my name in assignee
column.
1 min readFeb 5, 2024
- Here it is: a simple 4-liner containing the pattern
SELECT assignee, COUNT(*) as ticket_count
FROM tickets
GROUP BY assignee
ORDER BY ticket_count DESC;
Use the SELECT
statement to retrieve the desired columns.
- Utilize the
COUNT(*)
function to calculate the count of all rows - Group the result set using the
GROUP BY
a clause specifying the value you want to count - in my case how many tickets were assigned to me - Sort the result set in descending order using the
ORDER BY
clause withDESC
.
By following this pattern, you can retrieve counts of a certain value and sort them in descending order to analyze and prioritize your data effectively.