J'ai deux tables Client
et Instructor
.
Table client:
id_client|name_client|FK_instructor ---------+-----------+------------ 1 | Clinton | 2 2 | Gates` | 1 3 | Bush | 1 4 | Clinton | 2 5 | Obama | 1 6 | Jack | 3
Table d'instructeur:
id_instructor|name_instructor -------------+--------------- 1 | Sara 2 | Sam 3 | Dean 4 | Julie 5 | Jake
Je veux sélectionner les 3 instructeurs qui ont le less de clients associés.
Merci d'avance.
Maintenant que vous avez mentionné que vous utilisez SQL Server, en plus de GROUP BY
et ORDER BY
vous avez besoin d'un TOP(3)
sur votre 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
Notez que j'ai ajouté l'identifiant d'instructeur au groupe par rapport à l'autre réponse dans le cas où plus d'un instructeur a le même nom.
Si vous travaillez avec Netezza , vous pouvez essayer:
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
Il y a une excellente documentation pour Netezza ici: http://www-304.ibm.com/support/knowledgecenter/SSULQD_7.2.0/com.ibm.nz.dbu.doc/c_dbuser_sql_grammar.html
Il y a aussi des tutoriels SQL ici: http://www.w3schools.com/sql/