2016-09-23 46 views
1

表內提取公共的數據,我有以下Vehicle表:沒有動態查詢或相交

enter image description here

從中我想每Index值的車輛ID /名稱,即以下結果

enter image description here

我已能產生這種結果的動態查詢:

select vehicleId,vehicleName from Vehicle where [Index] = 1 
intersect 
select vehicleId,vehicleName from Vehicle where [Index] = 2 
intersect 
select vehicleId,vehicleName from Vehicle where [Index] = 3 

但我不能使用具有所有可能的Index值的動態查詢。

我需要一個涉及自加入或一些非動態SQL技術來執行相同的解決方案。可能嗎?

回答

2

使用group byindex找到vehicleId, vehicleName組合:

select vehicleId, vehicleName 
from Vehicle 
group by vehicleId, vehicleName 
having count(distinct [index]) = (select count(distinct [Index]) from Vehicle) 
+1

count(distinct [index])> 1自從本田和鈴木以來都出現了兩次,因爲它們出現兩次。它應該是「有count(distinct [IndexId])= MAX(indexid)」。請更新您的答案,我會接受它。 :) – StackAddict

+0

啊。你想要的車輛具有*每個*索引....查看更新回答 – Bohemian

+1

請注意'max(index)'是不安全的,因爲索引號可能有間隙 – Bohemian

0

也許這是更爲清晰的CTE?

WITH I_LIST AS (
    SELECT DISTINCT Index 
    FROM Vehicle 
) 
SELECT V.VehicleId, V.VehicleName 
FROM I_LIST 
LEFT JOIN Vehicle V ON I_List.Index = V.Index 
GROUP BY V.VehicleId, V.VehicleName 
HAVING COUNT(I_List.Index) = (SELECT COUNT(*) FROM I_LIST)