有很多方法可以爲一隻貓皮膚...測試每一種方法以找出哪種方法在桌子設計和RDBMS方面表現更好。我相當肯定我也錯過了一些出路。
帶窗口的功能
SELECT *
FROM ( SELECT Event.EventID,
Event_Reps.LastName ,
Event_reps.FirstName,
Cost.EventDate,
MAX(Cost.EventDate) OVER(PARTITION BY EventID) [MaxEventDate]
FROM Cost WITH(NOLOCK)
INNER JOIN Event WITH(NOLOCK)
ON Cost.EventID = Event.EventID
INNER JOIN Event_Reps WITH(NOLOCK)
ON Cost.EventRep = Event_Reps.EventRep
WHERE Event.EventID = 66
AND Event_Reps.Division = 'Houston'
AND Cost.CostAmt = 0
) as table1
WHERE MaxEventDate = EventDate
OR
SELECT *
FROM ( SELECT Event.EventID,
Event_Reps.LastName ,
Event_reps.FirstName,
Cost.EventDate,
ROW_NUMBER() OVER(PARTITION BY EventID ORDER BY Cost.EventID) [RowNumber]
FROM Cost WITH(NOLOCK)
INNER JOIN Event WITH(NOLOCK)
ON Cost.EventID = Event.EventID
INNER JOIN Event_Reps WITH(NOLOCK)
ON Cost.EventRep = Event_Reps.EventRep
WHERE Event.EventID = 66
AND Event_Reps.Division = 'Houston'
AND Cost.CostAmt = 0
) as table1
WHERE RowNumber = 1
或聚集
SELECT *
FROM ( SELECT Event.EventID,
Event_Reps.LastName ,
Event_reps.FirstName,
Cost.EventDate,
ROW_NUMBER() OVER(PARTITION BY EventID ORDER BY Cost.EventID) [RowNumber]
FROM Cost WITH(NOLOCK)
INNER JOIN Event WITH(NOLOCK)
ON Cost.EventID = Event.EventID
INNER JOIN Event_Reps WITH(NOLOCK)
ON Cost.EventRep = Event_Reps.EventRep
INNER JOIN
( SELECT EventID, MAX(EventDate) [EventDate]
FROM Cost
GROUP BY EventID
) MaxCost
ON MaxCost.EventID = Cost.EventID
AND MaxCost.EventDate = Cost.EventDate
WHERE Event.EventID = 66
AND Event_Reps.Division = 'Houston'
AND Cost.CostAmt = 0
) as table1
或連接的
SELECT *
FROM ( SELECT Event.EventID,
Event_Reps.LastName ,
Event_reps.FirstName,
Cost.EventDate,
ROW_NUMBER() OVER(PARTITION BY EventID ORDER BY Cost.EventID) [RowNumber]
FROM Cost WITH(NOLOCK)
INNER JOIN Event WITH(NOLOCK)
ON Cost.EventID = Event.EventID
INNER JOIN Event_Reps WITH(NOLOCK)
ON Cost.EventRep = Event_Reps.EventRep
LEFT JOIN Cost c2
ON c2.EventID = Cost.EventID
AND c2.EventDate > Cost.EventDate
WHERE Event.EventID = 66
AND Event_Reps.Division = 'Houston'
AND Cost.CostAmt = 0
AND Cost.EventID IS NULL
) as table1
或者雖然存在
SELECT *
FROM ( SELECT Event.EventID,
Event_Reps.LastName ,
Event_reps.FirstName,
Cost.EventDate,
ROW_NUMBER() OVER(PARTITION BY EventID ORDER BY Cost.EventID) [RowNumber]
FROM Cost WITH(NOLOCK)
INNER JOIN Event WITH(NOLOCK)
ON Cost.EventID = Event.EventID
INNER JOIN Event_Reps WITH(NOLOCK)
ON Cost.EventRep = Event_Reps.EventRep
WHERE Event.EventID = 66
AND Event_Reps.Division = 'Houston'
AND Cost.CostAmt = 0
AND NOT EXISTS
( SELECT 1
FROM Cost c2
WHERE c2.EventID = Cost.EventID
AND c2.EventDate > Cost.EventDate
)
) as table1
您正在使用什麼版本的SQL
? – 2012-03-06 16:02:54
**什麼是**數據庫系統,以及哪個版本? ** SQL **只是結構化查詢語言(Structured Query Language) - 許多數據庫系統使用的語言 - SQL是** NOT **數據庫產品......類似這樣的東西通常是供應商特定的 - 所以我們真的需要知道什麼您正在使用的數據庫系統.... – 2012-03-06 16:30:29