将子查询转换为结束

时间:2014-10-02 21:01:08

标签: sql sql-server-2012

您可以转换此查询,例如优化以进行咨询,是根据版本启动,它是同一个表。

select MAX(y.Version),
 y.Unidad,
 y.RutCompañia,
 y.Cobertura,
 y.Temporada,
 y.PorcentajeSubsidio,y.RendimientoInferior,y.RendimientoSuperior 
from ddbb.dbo.NS_CA y 
where y.IDVariedad='010101' and y.Temporada ='2011'
and y.ZHS='CA0607'
and y.Moneda='UF'
and y.Version in (select MAX(x.Version) from ddbb.dbo.NS_CA  x where x.IDVariedad='010101' and x.Temporada ='2011'
and x.ZHS='CA0607'
and x.Moneda='UF')
group by y.Unidad,y.RutCompañia,y.Cobertura,y.Temporada,y.PorcentajeSubsidio,y.RendimientoInferior,y.RendimientoSuperior

我想象了这样的事情

select  MAX(b.Version) OVER(PARTITION BY b.IDVariedad,b.IDRubro ) as maximo 

但它无法正常工作

谢谢。

修改

感谢您的翻译和答案。 添加更多信息,例如我有下一个表(tabla):

| Version    | Temporada   | Unidad       | etc          |
|:-----------|------------:|:------------:|:------------:|
| 00         |        2011 |    N         |  xx          |
| 00         |        2011 |    N         |  xx          |
| 01         |        2011 |    N         |  xx          |
| 02         |        2011 |    N         |  xx          |
| 03         |        2011 |    N         |  xx          |
| 03         |        2011 |    N         |  xx          |

和我将生成的查询是:

select * from tabla a
where a.version in (select max(b.Version) from tabla b where b.Temporada='2011')


    | Version    | Temporada   | Unidad       | etc          |
    | 03         |        2011 |    N         |  xx          |
    | 03         |        2011 |    N         |  xx          |

是可能的更改子查询到分区' ? ,谢谢

2 个答案:

答案 0 :(得分:0)

WITH cte as
(SELECT ROW_NUMBER() OVER (ORDER by y.Version DESC) row_id
    ,   y.Unidad
    ,   y.RutCompañia
    ,   y.Cobertura
    ,   y.Temporada
    ,   y.PorcentajeSubsidio
    ,   y.RendimientoInferior
    ,   y.RendimientoSuperior
FROM ddbb.dbo.NS_CA y
WHERE y.IDVariedad = '010101'
    AND y.Temporada = '2011'
    AND y.ZHS = 'CA0607'
    AND y.Moneda = 'UF'
    AND y.Version)


SELECT * FROM cte
where row_id = 1

答案 1 :(得分:0)

似乎你想要这个:

select MAX(y.Version),
 y.Unidad,
 y.RutCompañia,
 y.Cobertura,
 y.Temporada,
 y.PorcentajeSubsidio,y.RendimientoInferior,y.RendimientoSuperior 
from y.Version =
     (select MAX(x.Version) 
        from ddbb.dbo.NS_CA  x 
       where x.IDVariedad=y.IDVariedad and x.Temporada = y.Temporada
             and x.ZHS=y.ZHS   and x.Moneda=y.Moneda)
group by y.Unidad,y.RutCompañia,y.Cobertura,y.Temporada,y.PorcentajeSubsidio,y.RendimientoInferior,y.RendimientoSuperior

请参阅Why no windowed functions in where clauses?