假設這是你的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