I want to exclude records where id > 5 then select the top 1 of it order by date. How can I achieve this? Each record has audit_line which is unique field for each record. Recent SQL script is on below:
SELECT * 
FROM db.table 
HAVING COUNT(id) > 5
I want to exclude records where id > 5 then select the top 1 of it order by date. How can I achieve this? Each record has audit_line which is unique field for each record. Recent SQL script is on below:
SELECT * 
FROM db.table 
HAVING COUNT(id) > 5
 
    
    If you want id > 5 then you want where:
select top (1) t.*
from db.table t
where id > 5
order by date;
 
    
    You can use row-numbering for this.
Note that if you have no other column to order by, you can do ORDER BY (SELECT NULL), but then you may get different results on each run.
SELECT *
FROM (
    SELECT *, ROW_NUMBER() OVER (PARTITION BY id ORDER BY some_other_column) rn
    FROM table
) t
WHERE rn = 5;
