sql >> Base de Datos >  >> RDS >> Sqlserver

Ajuste de consulta SQL

; WITH valid_positions AS (
  SELECT MMSI
       , Message_ID
       , "Time"
       , Latitude
       , Longitude
  FROM   dbo.DecodedCSVMessages_Staging
  WHERE  Latitude  > 55
  AND    Latitude  < 85
  AND    Longitude > 50
  AND    Longitude < 141
)
, positions AS (
  SELECT MMSI
       , Message_ID
       , "Time"
       , Latitude
       , Longitude
  FROM   dbo.DecodedCSVMessages_Staging
  WHERE  Message_ID IN (1, 3)
  AND    EXISTS (
           SELECT *
           FROM   valid_positions
           WHERE  valid_positions.MMSI = DecodedCSVMessages_Staging.MMSI
         )
)
, details AS (
  SELECT MMSI
       , Ship_Type
       , Vessel_Name
       , Row_Number() OVER (PARTITION BY MMSI ORDER BY "Time" DESC) As row_num
  FROM   dbo.DecodedCSVMessages_Staging
  WHERE  Message_ID = 5
)
SELECT positions.MMSI
     , positions.Message_ID
     , positions."Time"
     , details.Ship_Type
     , details.Vessel_Name
     , positions.Latitude
     , positions.Longitude
FROM   positions
 INNER
  JOIN details
    ON details.MMSI    = positions.MMSI
   AND details.row_num = 1 -- Limit to "latest" ship details per MMSI

Ahora se está utilizando un tercer CTE.

  1. valid_positions :cualquiera registros donde las coordenadas se ajustan a sus criterios, para cualquier Message_ID 2)
  2. positions :todos los registros donde Message_ID es igual a 1 o 3 y hay un registro en el MMSI correspondiente en valid_positions
  3. details :sin cambios desde antes. Muestra los detalles "más recientes" del barco/nave (Message_ID =5)