获取此输出的SQL Server查询

时间:2012-07-26 09:12:08

标签: sql sql-server database sql-server-2008-r2

我有一个查询,我无法获得输出。 以下是要执行的查询

问:2。编写查询以查找已获得最大车辆数量的城市名称,ID和计数。

现在,Given是应该在其上执行查询的一个表。

Vehicle_Detail_ID   City_ID
56                    242
57                    242
58                    242
59                    243
60                    241
61                    242
62                    245

另一张具有城市名称

的表格
City_ID City_Name
242          Bangalore
243          ChamarajNager
241          Bellary
245          Chitradurga

预期输出:

City_ID No_Vehicles
242          4

请告诉我如何编写提取正确输出的查询。

以下是给出城市Id及其车辆数量的查询。 试过:

SELECT c.city_id, COUNT(c.City_ID) AS NO_vehicles
  FROM city c, vehicle_details v 
 WHERE c.City_ID = v.City_ID
 GROUP BY c.City_ID

实际输出

City_ID No_Vehicles
242             4
243             1
241             1
245             1

请按照预期输出中所示帮助我获得最大值。

5 个答案:

答案 0 :(得分:1)

//解决方案1 ​​

Select top 1 v.cityID,count(*) as c 
from tblVehicle as v 
group by cityID
order by c desc

//带有cityName的解决方案2

Select top 1 a.cityID,a.cityName,Count(*) as c 
from tblCity as a
inner join tblVehicle as b
    on a.cityID=b.cityID
group by a.cityID,a.cityName
order by c desc

答案 1 :(得分:0)

尝试

select TOP 1 c.city_id,COUNT(c.City_ID) as NO_vehicles 
from city c,vehicle_details v 
where c.City_ID=v.City_ID 
group by c.City_ID.

答案 2 :(得分:0)

CREATE TABLE V_ddetails(Vehicle_Detail_ID int,City_ID int)
INSERT INTO V_ddetails 
VALUES(56,242),(57,242),(58,242),(59,243),(60, 241),(61,242),(62,245)

CREATE TABLE city(City_ID int, City_Name varchar(50))

INSERT INTO city
VALUES(242,'Bangalore'),(243,'ChamarajNager'),(241,'Bellary'),(245,'Chitradurga')

select top 1 v.City_ID,COUNT(*) as No_Vehicles from V_ddetails v inner join city c
on v.City_ID =c.City_ID 
group by v.City_ID 
order by No_Vehicles desc

答案 3 :(得分:0)

我认为使用分区功能和CTE可以执行此操作ON FIDDLE

CREATE TABLE V_details(Vehicle_Detail_ID int,City_ID int) 
INSERT INTO V_details  
VALUES
(56,242),
(57,242),
(58,242),
(59,243),
(60, 241),
(60, 241),
(60, 241),
(60, 241),
(61,242),
(62,245)  

CREATE TABLE city(City_ID int, City_Name varchar(50))  
INSERT INTO city 
VALUES
(242,'Bangalore'),
(243,'ChamarajNager'),
(241,'Bellary'),
(245,'Chitradurga') 




   ;with initdata_cte as  
(     
  SELECT              
  c.city_id             
  , COUNT(c.City_ID) AS NO_vehicles                
  , RANK() over (order by c.city_id) rnk     
  FROM city c, V_details v        
  WHERE c.City_ID = v.City_ID       
  GROUP BY c.City_ID  
) 
, rnk_cte as 
(     
  SELECT              
  city_id             
  , NO_vehicles                
  , RANK() over (order by NO_vehicles desc) rnk     
  FROM initdata_cte     
) 
select * from rnk_cte where rnk =1 

答案 4 :(得分:-1)

CREATE TABLE V_ddetails(Vehicle_Detail_ID int,City_ID int)
INSERT INTO V_ddetails 
VALUES(56,242),(57,242),(58,242),(59,243),(60, 241),(61,242),(62,245)

select City_ID,COUNT(*) as No_Vehicles  from V_ddetails 
where city_id=242
group by City_ID