在sql server中使用has和order by

时间:2014-07-16 17:42:48

标签: sql sql-server select inner-join

我想要选择多次出现的列sanciones.matricula_vehiculo的元素,下一个代码显示所有元素;但是缺少类似于>的限制。 1

SELECT 
vehiculos.marca_vehiculo, 
sanciones.matricula_vehiculo, 
vehiculos.modelo_vehiculo

FROM vehiculos
INNER JOIN sanciones
ON vehiculos.matricula_vehiculo=sanciones.matricula_vehiculo
ORDER BY vehiculos.marca_vehiculo;

3 个答案:

答案 0 :(得分:0)

我认为这可以满足您的需求:

SELECT marca_vehiculo, matricula_vehiculo, modelo_vehiculo
FROM (SELECT v.marca_vehiculo, s.matricula_vehiculo, v.modelo_vehiculo,
             COUNT(*) OVER (PARTITION BY s.matricula_vehiculo) as cnt
      FROM vehiculos v INNER JOIN
           sanciones s
           ON v.matricula_vehiculo = s.matricula_vehiculo
     ) vs
WHERE cnt > 1
ORDER BY marca_vehiculo;

答案 1 :(得分:0)

SELECT matricula_vehiculo
FROM vehiculos
INNER JOIN sanciones ON vehiculos.matricula_vehiculo=sanciones.matricula_vehiculo
GROUP BY matricula_vehiculo
HAVING count(*) > 1
ORDER BY vehiculos.marca_vehiculo

答案 2 :(得分:0)

这也可以,并且您不会使用EXISTS:

来获得JOIN的开销
SELECT 
    vehiculos.marca_vehiculo, 
    vehiculos.matricula_vehiculo, 
    vehiculos.modelo_vehiculo
FROM vehiculos v
WHERE EXISTS (  SELECT *
                FROM sanciones s 
                WHERE s.matricula_vehiculo = v.matricula_vehiculo
                HAVING COUNT(*) > 1 )
ORDER BY vehiculos.marca_vehiculo;