0

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.

4

4 回答 4

4

在 sql server 2005+ 中,您可以使用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

请参阅带有演示的 SQL Fiddle

或者您可以使用子查询来获取最短时间:

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';
于 2012-12-04T16:40:47.900 回答
1

试试这个

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' 
于 2012-12-04T16:49:27.747 回答
1
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
于 2012-12-04T16:40:11.037 回答
1

您可以使用outer apply,例如:

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'
于 2012-12-04T16:40:31.477 回答