选择在其他特定表中作为外键最多的行

时间:2016-09-10 18:43:47

标签: sql sql-server

我有这张表给操作员:

+--------------------------------+
|   ProviderID  | ProviderName   |
+---------------+----------------+
|        1      |   Movistar     |
+---------------+----------------+
|        2      |   Vadafone     |
+---------------+----------------+
|        3      |   Orange       |
+---------------+----------------+

此外,我还有这些运营商提供的计划表。 (简化版):

+--------------------------------+
|   PlanID      |   ProviderID   |
+---------------+----------------+
|        1      |   2            |
+---------------+----------------+
|        2      |   2            |
+---------------+----------------+
|        3      |   2            |
+---------------+----------------+
|        4      |   1            |
+---------------+----------------+
|        5      |   3            |
+---------------+----------------+

我想只打印那些计划最多的提供商。这就是我到目前为止所做的:

SELECT O.ProviderId, COUNT(Pl.ProviderId) as numberOfPlans
FROM Plan Pl
INNER JOIN Provider O ON O.ProviderId= P.ProviderId
GROUP BY O.ProviderName

这会打印所有提供商名称和计划数量,而我只需打印那些计划最多的计划,因此在这种情况下,只有Vadafone才有3个计划。 (如果其他提供商具有相同的最大计划价值,也会打印出来)。 对不起,问题,我不知道我应该如何确定问题。

2 个答案:

答案 0 :(得分:0)

order by numberOfPlans喜欢

SELECT O.ProviderId, 
COUNT(Pl.ProviderId) as numberOfPlans
FROM Plan Pl
INNER JOIN Provider O ON O.ProviderId= P.ProviderId
GROUP BY O.ProviderName
ORDER BY numberOfPlans DESC;

答案 1 :(得分:0)

如果您使用的是SQL Server,则可以使用TOP。例如,要获得计划最多的提供商之一:

SELECT TOP 1 pl.ProviderId, COUNT(*) as numberOfPlans
FROM Plan pl
GROUP BY pl.ProviderId
ORDER BY numberOfPlans DESC;

在其他数据库中,这通常是:

SELECT pl.ProviderId, COUNT(*) as numberOfPlans
FROM Plan pl
GROUP BY pl.ProviderId
ORDER BY numberOfPlans DESC
FETCH FIRST 1 ROW ONLY;

或:

SELECT pl.ProviderId, COUNT(*) as numberOfPlans
FROM Plan pl
GROUP BY pl.ProviderId
ORDER BY numberOfPlans DESC
LIMIT 1;

如果有联系,那么在SQL Server中你可以这样做:

SELECT TOP (1) WITH TIES pl.ProviderId, COUNT(*) as numberOfPlans
FROM Plan pl
GROUP BY pl.ProviderId
ORDER BY numberOfPlans DESC;

注意:

  • 您不需要JOINProvider表,因为ProviderId位于Plan表中。
  • GROUP BY条件应与SELECT
  • 中的列相同