0

还有其他方法可以编写此查询吗?我尝试在子查询中执行此操作,但由于有多个列,它不起作用。看起来这个查询只能自己工作。请纠正我

记录

PK记录Id

日期查看

看车

我试过这个

   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

然后我尝试了这个

   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

在我尝试过的许多其他查询中,我不知道如何让它工作。

简而言之,对于特定日期,我想获取查看次数最多的汽车。

喜欢:日期查看最喜欢的CarOfTheDay

2012-09-22 | Nissan

2012-09-23 | BMW
4

3 回答 3

0

我认为以下应该有效(免责声明,不是我自己的全部工作,改编自另一个问题的答案)

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
于 2013-04-12T15:02:55.267 回答
0

尝试这个

   SELECT R.`dateViewed` ,COUNT(R.CarViewed) as cnt ,R.CarViewed FROM Records R
   GROUP BY R.`dateViewed 
   ORDER BY COUNT(R.CarViewed) DESC 
于 2013-04-12T14:41:46.403 回答
0

这样的事情在 MySQL 中真的很糟糕,所以它实际上可能比两个相关的子查询慢,但至少它返回汽车和它的视图计数:

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
于 2013-04-12T15:09:45.470 回答