我在 SQL 中有一个名为 Questionnaire 的表,其中有名为 ID、Newspaper 和 CreditCards 的列。我需要输出至少拥有 3 张信用卡的 ID 中最受欢迎的报纸。
例子:
身份证信用卡报纸 -------------------------------------- 10354 3 独立 12154 4 独立 11354 2时代 14587 3 每日邮报 19874 5 星期日新闻 16847 1 独立报
你能帮忙用一个sql命令来输出上述查询吗?
select *
from (
select newspaper,
rank() over (order by count(*) desc) as rnk
from Questionnaire
where credit_cards >= 3
group by newspaper
) t
where rnk = 1
如果两张报纸具有相同的“人气”,则两者都将被退回。
SQLFiddle 演示:http ://sqlfiddle.com/#!4/16dcb/1
如果您只想获取最受欢迎的报纸[s],那么这可以解决查询。
select
newspaper
, count(1) as fct
from
Questionnaire
where
CreditCards >= 3
group by newspaper
having fct =
(
select
max(ct)
from
(
select
newspaper
,count(1) as ct
from
Questionnaire
where
CreditCards >= 3
group by newspaper
)
)
/