Reputation: 5623
In SQL Server, I have two tables. One "main" table with all the data and a unique id
per entry. The other table is an audit log, where that id
from main will be stored multiple times in the audit table.
My query looks like:
SELECT
a.title, a.id, a.name, t.user, t.time
FROM
MainTable a
INNER JOIN
AuditLog AS t ON a.id = t.id
WHERE
a.NAME LIKE 'Something%'
AND a.ACTIVE = 'Y'
Which gives a result like:
TITLE ID NAME USER TIME
----------------------------------------------------------------
Something1 someth1 Some 1 User5 468534771
Something1 someth1 Some 1 User7 468574887
Something2 someth2 Some 2 User6 468584792
Which returns multiple results of the ID. I only want the oldest (from AuditLog
) entry and not every one. So the result I would want looks like:
TITLE ID NAME USER TIME
----------------------------------------------------------------
Something1 someth1 Some 1 User5 468534771
Something2 someth2 Some 2 User6 468584792
How can this be done? I'm trying some subqueries within the join.
Upvotes: 0
Views: 215
Reputation: 247630
In sql server 2005+, you can use row_number()
select title, id, name, user, time
from
(
SELECT a.title, a.id, a.name, t.user, t.time,
row_number() over(partition by a.id order by t.time) rn
FROM MainTable a
INNER JOIN AuditLog AS t
ON a.id = t.id
WHERE a.NAME LIKE 'Something%'
AND a.ACTIVE='Y'
) src
where rn = 1
Or you can use a sub-query to get the min time:
SELECT a.title, a.id, a.name, l.user, l.time
FROM MainTable a
INNER JOIN AuditLog l
ON a.id = l.id
INNER JOIN
(
select min(time) Mintime, id
from AuditLog
group by id
) AS t
ON l.id = t.id
AND l.time = t.mintime
WHERE a.NAME LIKE 'Something%'
AND a.ACTIVE='Y';
Upvotes: 4
Reputation: 36638
Give this a try
SELECT a.title, a.id, a.name, t.user, t.time
FROM MainTable a
JOIN AuditLog AS t ON a.id = t.id
JOIN (SELECT ID, MAX(TIME) AS LASTTIME FROM AUDITLOG) AS c
ON c.ID = t.id AND c.LASTTIME = t.time
WHERE a.NAME LIKE 'Something%'
AND a.ACTIVE = 'Y'
Upvotes: 1
Reputation: 238048
You could use outer apply
, like:
select *
from MainTable a
outer apply
(
select top 1 *
from AuditLog t
where a.id = t.id
order by
t.time
) t
where a.name like 'Something%'
and a.active = 'y'
Upvotes: 1
Reputation: 3356
SELECT TOP 1 a.title, a.id, a.name, t.user, t.time
FROM MainTable a
INNER JOIN AuditLog AS t
ON a.id = t.id
WHERE a.NAME LIKE 'Something%'
AND a.ACTIVE='Y'
ORDER BY T.DATE DESC
Upvotes: 1