这是表格: 用户
Name: Subject:
Peter Math
Mary Chinese
Mary Computer
Mary Hist
Mary PE
Mary English
Peter Art
Chris English
Chris Computer
Peter Computer
Paul Math
我希望顶部出现在名称中,并返回前4个结果应该是主题名称。例如,在这种情况下,top出现名称是Mary,并且基于主题,中文,计算机,英语的顺序,所以我希望得到结果:
Mary Chinese
Mary Computer
Mary English
Mary Hist
如果Mary不是最能显示结果,那么第二个人就会跟随,就像,表格会这样:
Name: Subject:
Peter Math
Mary Chinese
Mary Computer
Mary Hist
Peter Art
Chris English
Chris Computer
Peter Computer
Paul Math
结果将是,
Mary Chinese
Mary Computer
Mary Hist
Peter Art
因为玛丽是最出现的,所以玛丽会回来,但玛丽不足以填补4个位置,所以第二个出现的位置将取代,在这种情况下,我们使用彼得。
答案 0 :(得分:5)
SELECT user.name, user.subject FROM user INNER JOIN ( SELECT name, COUNT(1) AS occurrences FROM user GROUP BY name ) AS user_occurrences ON user.name = user_occurrences.name ORDER BY user_occurrences.occurrences DESC, user.name ASC, user.subject ASC LIMIT 4
编辑这可能会更好,具体取决于您使用的RDBMS和数据集的大小。尝试两者并进行比较。
SELECT user.name, user.subject FROM user INNER JOIN user AS user_occurrences ON user.name = user_occurrences.name GROUP BY user.name --, user.subject Second GROUP BY not needed on MySQL, but it should logically be there ORDER BY COUNT(user_occurrences.subject) DESC, user.name ASC, user.subject ASC LIMIT 4
答案 1 :(得分:1)
按名称,主题和按计数排序
从组中选择前4名MSSQL代码:
select top 4 q.marketname, cc.countryname from (
select top 100 m.MarketName, m.MarketId, COUNT(m.marketname) as [count]
from Common.Country c inner join Common.Market m on c.MarketId = m.MarketId
group by m.MarketName, m.MarketId order by COUNT(m.marketname) desc)
q inner join Common.Country cc
on cc.MarketId = q.MarketId order by [Count] desc
您可以制作类似的mySQL代码
这是相关的MySQL代码
select q.name, cc.subject from (
select m.Name, count(*) as Count
from User m
group by m.Name
order by COUNT(*) desc
LIMIT 100
) q
inner join user cc on cc.Name= q.name
order by Count desc
LIMIT 4
这是经过深思熟虑的,你想要解决方案吗?你不能在你的技术中实现逻辑吗?如果不了解建议的解决方案,就不应该进行投票。