SQL Server:具有最少子项的父ID

时间:2016-01-07 00:19:36

标签: sql-server select join

我有两张表ClientInstructor

客户表:

id_client|name_client|FK_instructor
---------+-----------+------------
    1    | Clinton   |    2
    2    | Gates`    |    1
    3    | Bush      |    1
    4    | Clinton   |    2
    5    | Obama     |    1
    6    | Jack      |    3

讲师表:

id_instructor|name_instructor
-------------+---------------
      1      |    Sara
      2      |    Sam            
      3      |    Dean
      4      |    Julie
      5      |    Jake

我想选择关联客户数最少的3位教师。

提前谢谢。

2 个答案:

答案 0 :(得分:3)

既然您提到您正在使用SQL Server,那么除了GROUP BYORDER BY之外,您需要TOP(3)上的SELECT

SELECT   TOP(3) i.id_instructor, i.name_instructor
FROM     Instructor i
JOIN     Client c ON c.FK_instructor = i.id_instructor
GROUP BY i.id_instructor, i.name_instructor
ORDER BY COUNT(*) --Implicitly ascending

请注意,如果多个教师具有相同的名称,我将教师ID添加到组中,与其他答案进行比较。

答案 1 :(得分:1)

如果您使用 Netezza ,可以尝试:

SELECT name_instructor, COUNT(id_client)
FROM instructor_table
    JOIN client_table on instructor_table.id_instructor = client_table.FK_instructor
GROUP BY name_instructor
ORDER BY COUNT(id_client) DESC
LIMIT 3

这里有很棒的Netezza文档: http://www-304.ibm.com/support/knowledgecenter/SSULQD_7.2.0/com.ibm.nz.dbu.doc/c_dbuser_sql_grammar.html

这里还有SQL教程: http://www.w3schools.com/sql/