简体   繁体   English

如何编写与计数相关的查询

[英]How do I write a query related to count

I have two tables such as Car and Driver .我有两张表,例如CarDriver Car table has two columns. Car表有两列。 which are car_id and car_name .它们是car_idcar_name Driver table also has two columns. Driver表也有两列。 which are driver_id and car_type .它们是driver_idcar_type

Cars汽车

car_id car_id car_name车名
1 1 Audi奥迪
2 2 BMW宝马
3 3 Ferrari法拉利

Drivers驱动程序

driver_id driver_id car_type汽车类型
1 1 BMW宝马
1 1 Audi奥迪
1 1 Ferrari法拉利
2 2 Audi奥迪
2 2 Cheverolet雪佛兰
2 2 Tata塔塔
3 3 Ferrari法拉利

How do I find which driver is driving more than two cars?如何找到驾驶超过两辆车的司机?

By using the Having clause通过使用 Have 子句

SELECT Driver_id
FROM Driver
GROUP BY Driver_id
HAVING COUNT(*) > 1

Your tables have surrogate primary keys but the Driver table uses the car name, not id, to relate cars to drivers.您的表具有代理主键,但Driver表使用汽车名称而不是 id 将汽车与司机联系起来。

So you can find the drivers with more than one car without needing to join to the car table (unless you need the car_id value)所以你可以找到拥有不止一辆车的司机,而不需要加入 car 表(除非你需要car_id值)

The query needs to count the distinct type of car grouped by driver_id , having a count of car type greater than one.查询需要计算由driver_id分组的不同类型的汽车,汽车类型的计数大于一。

From the information in that sentence you should be able to look up how to write it in SQL ;)从该句子中的信息中,您应该能够查找如何用 SQL 编写它;)

If the Driver table has a unique constraint on the two fields driver_id / car_type then you can use the query Dijkgraaf posted and not worry about the type of car they drive.如果Driver表对两个字段driver_id / car_type具有唯一约束,那么您可以使用 Dijkgraaf 发布的查询,而不必担心他们驾驶的汽车类型。

From the data you have shown there can't be any referential constraint (foreign key) of the cars drivers drive because you have Cheverolet (sic), Tata , and Ferrari in the Driver table but those cars are not in the Car table.根据您显示的数据,驾驶员驾驶的汽车不能有任何参考约束(外键),因为您在Driver表中有Cheverolet (sic)、 TataFerrari但这些汽车不在Car表中。

SELECT Driver_id
FROM YourTable
Where COUNT(Driver_id) > 1

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM