I want to select the latest records from the DB in SQL Server. If only one item is selected the final output is this:
SELECT TOP(10) * from dbo.Eventos WHERE Tipo LIKE '%OS%' AND Distrito LIKE '%'
+ always added at the end:
ORDER BY Data DESC
NOTE: Distrito LIKE '%'
must stay as it sometimes is programatically changed to something other than %
.
If there are more items selected, the query gets one UNION
line added programatically for each item. At the end, the ORDER BY
is added as always. Example with all 4 items checked:
SELECT TOP(10) * from dbo.Eventos WHERE Tipo LIKE '%OS%' AND Distrito LIKE '%'
UNION ALL SELECT TOP(10) * from dbo.Eventos WHERE Tipo LIKE '%Rad%' AND Distrito LIKE '%'
UNION ALL SELECT TOP(10) * from dbo.Eventos WHERE Tipo LIKE '%Aci%' AND Distrito LIKE '%'
UNION ALL SELECT TOP(10) * from dbo.Eventos WHERE Tipo LIKE '%Out%' AND Distrito LIKE '%'
ORDER BY Data DESC
But this gives me the OLDEST 10 results for each WHERE
clause sorted BY Data DESC
.
How can i get the NEWEST X results for each item (WHERE
)?