Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>You need another join to the same table to pull back all the records with an MMSI that is in the result of your existing query. Something like this should do it:</p> <pre><code>; WITH positions AS ( SELECT MMSI , Message_ID , "Time" , Latitude , Longitude FROM dbo.DecodedCSVMessages_Staging WHERE Message_ID IN (1, 3) AND Latitude &gt; 55 AND Latitude &lt; 85 AND Longitude &gt; 50 AND Longitude &lt; 141 ) , all_positions AS ( SELECT MMSI , Message_ID , "Time" , Latitude , Longitude FROM dbo.DecodedCSVMessages_Staging WHERE Message_ID IN (1, 3) ) , 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 all_positions.MMSI , all_positions.Message_ID , all_positions."Time" , details.Ship_Type , details.Vessel_Name , all_positions.Latitude , all_positions.Longitude FROM positions INNER JOIN details ON details.MMSI = positions.MMSI AND details.row_num = 1 -- Limit to "latest" ship details per MMSI INNER JOIN all_positions ON positions.MMSI = all_positions.MMSI </code></pre> <p>EDIT (after feedback from Clockwork-Muse):</p> <p>Your original query will return duplicate rows when a ship reports more than once from within the desired area. To get rid of this, just use DISTINCT in the positions CTE:</p> <pre><code>; WITH positions AS ( SELECT DISTINCT MMSI , Message_ID , "Time" , Latitude , Longitude FROM dbo.DecodedCSVMessages_Staging WHERE Message_ID IN (1, 3) AND Latitude &gt; 55 AND Latitude &lt; 85 AND Longitude &gt; 50 AND Longitude &lt; 141 ) , all_positions AS ( SELECT MMSI , Message_ID , "Time" , Latitude , Longitude FROM dbo.DecodedCSVMessages_Staging WHERE Message_ID IN (1, 3) ) , 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 all_positions.MMSI , all_positions.Message_ID , all_positions."Time" , details.Ship_Type , details.Vessel_Name , all_positions.Latitude , all_positions.Longitude FROM positions INNER JOIN details ON details.MMSI = positions.MMSI AND details.row_num = 1 -- Limit to "latest" ship details per MMSI INNER JOIN all_positions ON positions.MMSI = all_positions.MMSI </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload