有没有其他方法可以编写此查询? 我尝试在子查询中执行它,但由于多列而无法工作。看起来这个查询只能单独使用。请纠正我
记录
PK recordId
dateViewed
CarViewed
我试过这个
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
在我尝试的许多其他查询中,我不知道如何让它工作。
简而言之,我希望得到最常见的汽车。
喜欢: dateViewed favouriteCarOfTheDay
2012-09-22 | Nissan
2012-09-23 | BMW
答案 0 :(得分:0)
试试这个
SELECT R.`dateViewed` ,COUNT(R.CarViewed) as cnt ,R.CarViewed FROM Records R
GROUP BY R.`dateViewed
ORDER BY COUNT(R.CarViewed) DESC
答案 1 :(得分:0)
我认为以下内容应该有效(免责声明,而不是我自己的所有工作,改编自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
答案 2 :(得分:0)
这样的事情在MySQL中真的很糟糕,所以它实际上可能比两个相关的子查询慢,但至少它会返回汽车和它的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