我有以下Vehicle
表:
我希望车辆ID /名称包含每个Index
值,即以下结果
我做了一个动态查询,可以产生这个结果:
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技术的解决方案来执行相同的操作。有可能吗?
答案 0 :(得分:2)
使用group by
查找每vehicleId, vehicleName
个index
个组合:
select vehicleId, vehicleName
from Vehicle
group by vehicleId, vehicleName
having count(distinct [index]) = (select count(distinct [Index]) from Vehicle)
答案 1 :(得分: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)