Question

I have a table called "reports"

it looks like:

user_id | report_post 
   1            2    
   2            2  
   3            2  
   4           10 

Now I want to list the first three entries at first, cause the reported post id "2" is 3 times in this table... i want so sort them by the maximum of entries.

Hope you guys understand... thanks alot

----edit------ my output have to look like this

report_post | entries
    2             3    
   10             1
Was it helpful?

Solution

SELECT *
FROM (
    SELECT user_id, report_post, COUNT(*) AS cnt
    FROM reports
    GROUP BY report_post
) c
ORDER BY cnt DESC

OTHER TIPS

Select report_post, Count(1) As Entries
From   reports
Group By Report_Post
Order By Count(1) DESC

With your edit, this does what you're asking:

select report_post, count(*) entries
from reports
group by report_post
order by entries desc

Use a subquery. This should do the trick in MySQL:

select * from reports 
order by (
   select count(*) from reports as reports_a
   where reports_a.report_post=reports.report_post
) desc;

(the above answer's your question before you edited it to change it's meaning)

For the edited question, it is a trivial example of a group by:

select report_post,count(*) as entries
from reports
group by report_post
order by entries desc;
SELECT report_post as report_post, count(report_post) as entries 
FROM `reports` group by `report_post`

Single query.

SELECT * FROM reports ORDER BY entries DESC

I'm a little unsure of what exactly you are asking. Are you just trying to get it to return entries where the report_post id is equal to "2"?

If that is the case, this should work:

SELECT * FROM reports WHERE report_post=2;

Sorry if I misunderstood your question.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top