2014-10-02 51 views
0

您可以将此查询转换为优化以进行咨询,是根据版本进行优化,它是同一张表。将一个子查询转换为

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 

,但它不能正常工作

谢谢。

编辑:

感谢您的翻译和答案。 添加更多的信息,通过例子,我有一个表(塔布拉):

| 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   | 

是可能变化的子查询“过度分区”?感谢

+0

请你的问题翻译成英文。如果您要讲的语言是葡萄牙语,请查看http://pt.stackoverflow.com/ – 2014-10-02 21:04:15

+0

我将SQL SERVER 2012从标题移动到标记。但它看起来不像SQL服务器,请相应调整 – Sebas 2014-10-02 23:17:45

回答

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 
+0

,显然没有正确表达我正在寻找的是提取特定年份和其他组合的最大'版本',谢谢。 – ncw2233 2014-10-03 13:53:03

+0

使用row_id = 1的select查询。这应该给你最大的版本,而不使用子查询 – 2014-10-05 03:13:01

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?