SQL选择最佳实践

时间:2009-07-29 22:17:26

标签: sql

以下工作,我只是想知道这是否是找到每个审计字段的最新值的正确方法。

USE tempdb
CREATE Table Tbl(
TblID Int,
AuditFieldID Int,
AuditValue Int,
AuditDate Date
)
GO
INSERT INTO Tbl(TblID,AuditFieldID,AuditValue,AuditDate) VALUES(1,10,101,'1/1/2001')
INSERT INTO Tbl(TblID,AuditFieldID,AuditValue,AuditDate) VALUES(2,10,102,'1/1/2002')
INSERT INTO Tbl(TblID,AuditFieldID,AuditValue,AuditDate) VALUES(3,20,201,'1/1/2001')
INSERT INTO Tbl(TblID,AuditFieldID,AuditValue,AuditDate) VALUES(4,20,202,'1/1/2009')


SELECT AuditFieldID,AuditValue,AuditDate
FROM Tbl A
WHERE TblID=
(SELECT TOP 1 TblID
FROM Tbl
WHERE AuditFieldID=A.AuditFieldID
ORDER BY AuditDate DESC
)

4 个答案:

答案 0 :(得分:1)

简单:

SELECT top 1 AuditFieldID,AuditValue,AuditDate 来自Tbl 由AuditDate DES订购

答案 1 :(得分:1)

有各种方法可以做到这一点。不同的方法表现不同。我鼓励你看看这个解释各种方法的博客。

Including an Aggregated Column's Related Values

答案 2 :(得分:1)

汇总/排名以获取关键和最新日期,加入以获得价值。

这假定SQL Server 2005 +

DECLARE @tbl Table (
TblID Int,
AuditFieldID Int,
AuditValue Int,
AuditDate Date
)

INSERT INTO @tbl(TblID,AuditFieldID,AuditValue,AuditDate) VALUES(1,10,101,'1/1/2001')
INSERT INTO @tbl(TblID,AuditFieldID,AuditValue,AuditDate) VALUES(2,10,102,'1/1/2002')
INSERT INTO @tbl(TblID,AuditFieldID,AuditValue,AuditDate) VALUES(3,20,201,'1/1/2001')
INSERT INTO @tbl(TblID,AuditFieldID,AuditValue,AuditDate) VALUES(4,20,202,'1/1/2009')


;WITH cLatest AS
(
    SELECT
        ROW_NUMBER() OVER (PARTITION BY AuditFieldID ORDER BY AuditDate DESC) AS Ranking,
        AuditFieldID, AuditDate
    FROM
        @tbl
)
SELECT
    A.AuditFieldID, A.AuditValue, A.AuditDate
FROM
    @tbl A
    JOIN
    cLatest C ON A.AuditFieldID = C.AuditFieldID AND A.AuditDate = C.AuditDate
WHERE
    C.Ranking = 1

答案 3 :(得分:0)

你不需要where语句,因为你已经从tbl A中选择并在同一个字段上选择。