如何通过关联表对行进行排序?

时间:2018-08-08 12:49:42

标签: sql

我必须进入表teamspayments,其中一个团队支付了很多款项:

payments:
  team_id reference teams.id

现在我想要查询以按付款方式对所有团队进行排序,怎么办?

4 个答案:

答案 0 :(得分:0)

大多数DBMS都支持fetch first子句,因此您可以:

select team_id, count(payments)
from payments p
group by team_id
order by count(payments) desc
fetch first 1 rows only;

如果您想要team_name,则可以执行JOIN

select t.id as team_id, t.name, count(p.payments)
from teams t join
     payments p
     on p.team_id = t.id
group by t.id, t.name
order by count(p.payments) desc
fetch first 1 rows only;

答案 1 :(得分:0)

我想op也需要团队名称

  select p.team_id,t.name as team_name, count(payments) as Number_of_payment
    from payments p
    inner join team t
    on p.team_id=t.team_id
    group by p.team_id,t.name
    order by count(payments) desc

答案 2 :(得分:0)

SELECT t.id, count(*)
FROM team t
JOIN payments p ON t.id = p.team_id
GROUP BY t.id
ORDER BY count(*) desc

答案 3 :(得分:0)

可以使用子查询来使其保持整洁和可读性

WITH count_payments AS
(
    SELECT COUNT(*) as count_of_payments,
           team_id
    FROM payments
    GROUP BY team_id
)
SELECT count_payments.count_of_payments,
       count_payments.team_id,
       teams.* --Replace * with what fields you want
FROM count_payments
INNER JOIN teams on teams.team_id = count_payments.team_id
ORDER BY count_payments.count_of_payments