开发者

How do I find the latest DateTime for each of my products in combination with another condition

Product:
开发者_JAVA百科ProductID
ProductName

StateLog:
StateLogID
ProductID (Foreign Key)
State (bit)
TimeStamp (DateTime)

I need to find the highest StateLog.TimeStamp for each StateLog.ProductID there have the StateLog.State = 0


try:

SELECT
    p.ProductID, p.ProductName, dt.MaxTimeStamp
    FROM Product p
        LEFT OUTER JOIN (SELECT
                            ProductID, MAX(TimeStamp) AS MaxTimeStamp
                            FROM StateLog
                            WHERE State = 0
                            GROUP BY ProductID
                        ) dt ON p.ProductID =dt.ProductID 
    ORDER BY p.ProductName

or just:

SELECT
   ProductID, MAX(TimeStamp) AS MaxTimeStamp
   FROM StateLog
   WHERE State = 0
   GROUP BY ProductID


WITH ProductTimeStamps AS
(
   SELECT ProductID, Max(TimeStamp) FROM SateLog WHERE State=0 GROUP BY ProductID
)
SELECT sl.StateLogID, sl.ProductID, sl.TimeStamp
FROM StateLog sl
INNER JOIN ProductTimeStamps pts ON pts.ProductID = sl.ProductID AND pts.TimeStamp = sl.TimeStamp
WHERE sl.State = 0
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜