Search code examples
sqljoinjdbccounthsqldb

INNER JOIN and COUNT in the same query


I am having trouble with putting together INNER JOIN and COUNT in the same query.

Tables are:

TABLE STREETS

ID | STREET_NAME
------------------------
1  | Elm street
2  | Some other street
3  | Unknown street
4  | Killer street
5  | Dead-end street




TABLE ACCIDENTS_STREETS

STREET_ID | ACCIDENT_ID
-----------------------
   2      | 4
   2      | 7
   2      | 2
   2      | 1
   5      | 3

I would like to get the street name where most accidents have occured.

This is for COUNT:

SELECT TOP 1 COUNT(STREET_ID) AS dangerous_street FROM ACCIDENTS_STREETS GROUP BY STREET_ID ORDER BY dangerous_street DESC

How to add INNER JOIN there to get only the name of the street?

Any advice is appreciated!


Solution

  • The Following should work

    SELECT TOP 1 S.STREET_NAME,COUNT(a.*) AS dangerous_street 
    FROM ACCIDENTS_STREETS A 
    inner Join STREET S on S.ID = A.STREET_ID 
    GROUP BY S.STREET_NAME ORDER BY dangerous_street DESC