views:

113

answers:

1

I`m having trouble trying to optimize this query with OVER (PARTITION BY ...) because the id field of the table containing the maxDate needs to relate to the other table.

The working query is:

 SELECT maxReadDate, Equip.idProtocol
      FROM Equip, 
      (  
          SELECT idEquip as idEquipTot, MAX(readDate) AS maxReadDate
          FROM Totalizer
          WHERE Totalizer.idEquip = xxx
          GROUP BY idEquip
      ) 
      WHERE Equip.idEquip = idEquipTot

What I am trying to do is something near that, but it didn't work:

 SELECT maxReadDate, Equip.idProtocol
      FROM Equip, 
      (  
          SELECT idEquip as idEquipTot, MAX(readDate) OVER (PARTITION BY idEquip) maxReadDate
          FROM Totalizer
      ) 
      WHERE Equip.idEquip = idEquipTot
      AND Equip.lastReadDate = maxReadDate
      AND idEquipoTot = xxx

Thanks.

The solution:

SELECT DISTINCT e.idProtocol, e.idEquip, MAX(t.readDate) 
      OVER (PARTITION BY e.idEquip) maxReadDate
 FROM    Equip e
 JOIN    Totalizer t
 ON      t.idEquip = e.idEquip
 WHERE   e.idEquip = ?
+2  A: 
SELECT  e.idProtocol, e.idEquip, MAX(t.readDate) OVER (PARTITION BY e.idEquip) maxReadDate
FROM    Equip e
JOIN    Totalizer t
ON      t.idEquip = e.idEquip
Quassnoi
Nice solution, but in that way is the max date pre-selected before you actually search the entire equip table? I was thinking of using a analytic function instead of doing a native join or sub-select, which I ended up doing.Cheers.
lucasarruda
You'll probably need a DISTINCT in there too.
Jeffrey Kemp
Yes, you need a distinct also.What I needed is to list no all max dates, but the max date from 1 specific equipment. Filtering and adding the DISTINCT made it work. Thanks, guys. Above the solution: SELECT DISTINCT e.idProtocol, e.idEquip, MAX(t.readDate) OVER (PARTITION BY e.idEquip) maxReadDate FROM Equip e JOIN Totalizer t ON t.idEquip = e.idEquip WHERE e.idEquip = ?
lucasarruda