在SQL Server中,我有两个表。一个“主”表,包含所有数据和每个条目唯一id
。另一个表是审计日志,其中来自main的id
将多次存储在审计表中。
我的查询如下:
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'
结果如下:
TITLE ID NAME USER TIME
----------------------------------------------------------------
Something1 someth1 Some 1 User5 468534771
Something1 someth1 Some 1 User7 468574887
Something2 someth2 Some 2 User6 468584792
返回ID的多个结果。我只想要最早的(来自AuditLog
)条目而不是每个条目。所以我想要的结果如下:
TITLE ID NAME USER TIME
----------------------------------------------------------------
Something1 someth1 Some 1 User5 468534771
Something2 someth2 Some 2 User6 468584792
如何做到这一点?我正在尝试连接中的一些子查询。
答案 0 :(得分: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
或者您可以使用子查询来获取最短时间:
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';
答案 1 :(得分: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
答案 2 :(得分: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'
答案 3 :(得分: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'