INNER JOIN and COUNT in the same query

2019-09-18 22:08发布

问题:

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!

回答1:

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


回答2:

try this...

After joining the streets table, you would have to use an aggregation function to get the name in the resultset

SELECT 
TOP 1 COUNT(STREET_ID) AS dangerous_street
, min( STREET_NAME) dangerous_STREET_NAME
FROM ACCIDENTS_STREETS acc
inner join STREETS str
on acc.STREET_ID=str.id
GROUP BY STREET_ID 
ORDER BY dangerous_street DESC