假设这是你的vechicle
表中的数据:
SELECT * FROM vehicle ORDER BY vehicle_id ;
vehicle_id | quote_id
---------: | -------:
1 | 100
2 | 100
3 | 100
4 | 101
5 | 102
6 | 102
7 | 103
你第一步将得到quote_id
名单,多少也有各自的。因为,在上表中,vehicle_id
是独一无二的,你只需要:
SELECT
quote_id, count(*) AS number_of_vehicles_quoted
FROM
vehicle
GROUP BY
quote_id ;
quote_id | number_of_vehicles_quoted
-------: | ------------------------:
100 | 3
101 | 1
102 | 2
103 | 1
第二步:从以前的查询,你只希望那些number_of_vehicles_quoted
> 1 这是可以做到的在GROUP BY
之后的HAVING
子句,其对GROUP
ed行进一步限制。
SELECT
quote_id,
count(*) AS number_of_vehicles_quoted
FROM
vehicle
GROUP BY
quote_id
HAVING
count(*) > 1 ;
quote_id | number_of_vehicles_quoted
-------: | ------------------------:
100 | 3
102 | 2
如果你不喜欢HAVING
,或感觉不舒服,你可以用另外一个包裹查询,然后执行:
SELECT
quote_id, number_of_vehicles_quoted
FROM
(SELECT
quote_id,
count(*) AS number_of_vehicles_quoted
FROM
vehicle
GROUP BY
quote_id
) AS q
WHERE
number_of_vehicles_quoted > 1 ;
第三步 :最后,计算(*)先前查询的行数:
SELECT
count(*) AS count_of_quotes_with_more_than_one_vehicle_id
FROM
(SELECT
quote_id,
count(*) AS number_of_vehicles_quoted
FROM
vehicle
GROUP BY
quote_id
HAVING
count(*) > 1
) AS quotes_with_more_than_one_vehicle_id ;
| count_of_quotes_with_more_than_one_vehicle_id |
| --------------------------------------------: |
| 2 |
您可以检查整个设置和步骤dbfiddle here。查询是普通的SQL,并与所有引擎的工作原理可在DBFiddle(除了甲骨文,它抱怨标识符太长了,如果我不那么冗长;-)
注1,将工作:您可以简化最后一个查询,因为您不使用最外层查询中的某些信息。这会加速它的一点,虽然不以显著方式:
SELECT
count(*) AS count_of_quotes_with_more_than_one_vehicle_id
FROM
(SELECT
-- quote_id, -- You actually don't use this one in the outer query
-- count(*) AS number_of_vehicles_quoted -- This neither
1
FROM
vehicle
GROUP BY
quote_id
HAVING
count(*) > 1
) AS quotes_with_more_than_one_vehicle_id ;
dbfiddle here
注2:如果您的vehicle_id
小号都不能保证是独一无二的,你会使用方法:
SELECT
count(*) AS count_of_quotes_with_more_than_one_vehicle_id
FROM
(SELECT
1
FROM
vehicle
GROUP BY
quote_id
HAVING
count(DISTINCT vehicle_id) > 1
) AS quotes_with_more_than_one_vehicle_id ;
@joanolo:但解决方案只是基本的标准SQL,它运行在每个DBMS上,我怀疑是否有更好/更差的执行解决方案。 – dnoeth