0

Is there any other way to write this query ? I tried doing it in a subquery but it doesn't work because of the multiple columns. It seems like this query only works by itself. Please correct me

Records

PK recordId

dateViewed

CarViewed

I tried this

   SELECT R.`dateViewed` FROM Records ,(
   SELECT R.CarViewed, COUNT(R.CarViewed) as cnt FROM  Records R
   GROUP BY R.CarViewed
   ORDER BY cnt DESC
   LIMIT 1 ) AS favouriteCarOfTheDay
   GROUP BY R.`dateViewed

Then I tried this

   SELECT R.`dateViewed` ,COUNT(R.CarViewed) as cnt FROM Records ,
   (
   SELECT R.CarViewed FROM  Records R
   GROUP BY R.CarViewed
   ORDER BY cnt DESC
   LIMIT 1 ) AS favouriteCarOfTheDay
   GROUP BY R.`dateViewed

Along many other queries I tried, I have no idea how to get it working.

In a nutshell for a specific date, I would like to get the most common cars that were viewed.

Like : dateViewed favouriteCarOfTheDay

2012-09-22 | Nissan

2012-09-23 | BMW
Marc
  • 29
  • 5

3 Answers3

0

try this

   SELECT R.`dateViewed` ,COUNT(R.CarViewed) as cnt ,R.CarViewed FROM Records R
   GROUP BY R.`dateViewed 
   ORDER BY COUNT(R.CarViewed) DESC 
echo_Me
  • 37,078
  • 5
  • 58
  • 78
0

I think the following should work (disclaimer, not all my own work, adapted from an answer at another question)

SELECT DISTINCT
    R.dateViewed,
    R.CarViewed
FROM Records R
WHERE
    R.dateViewed =
        (SELECT R2.dateViewed FROM
            (
                SELECT R1.dateViewed, COUNT(*) AS numViewed
                FROM Records R1 
                WHERE R1.CarViewed = R.CarViewed
                GROUP BY R1.dateViewed
                ORDER BY R1.numViewed DESC
            ) AS R2
            LIMIT 1
        )
ORDER BY r.dateViewed
Community
  • 1
  • 1
Andy Nichols
  • 2,952
  • 2
  • 20
  • 36
0

Such things are really awful to do in MySQL so it might actually by slower than two correlated subquery but at least it returns both the car and it's viewcount:

SELECT counts.`dateViewed`,counts.`CarViewed` as favourite_car, counts.cnt
FROM
(SELECT R.`dateViewed` ,R.`CarViewed`, COUNT(*) as cnt 
FROM Records
GROUP BY R.`dateViewed` ,R.`CarViewed`
) as counts JOIN
(SELECT R.`dateViewed`, MAX(cnt) as cnt
FROM
(SELECT R.`dateViewed` ,R.`CarViewed`, COUNT(*) as cnt 
FROM Records
GROUP BY R.`dateViewed` ,R.`CarViewed`
) as q
GROUP BY R.`dateViewed`) as maxes
ON counts.cnt=maxes.cnt
Jakub Kania
  • 15,665
  • 2
  • 37
  • 47