我有一张表TableA
,数据如下:
PostID PostComments PostTransDate UserID
-----------------------------------------------------------------
10000 VRDFHFGFTR 2013-10-26 21:08:19.817 43434
10000 GFDGDFSDFF 2013-10-26 21:12:32.323 67576
10000 HGFHGFBNBF 2013-10-26 21:43:43.545 3232
10000 JNFNGHFGHG 2013-10-26 21:45:46.656 768
10000 MJHJNGJHGH 2013-10-26 21:56:32.767 9897
10001 XCVGFDGDFG 2013-10-26 22:54:54.868 3424
10001 YTUGFGHHGF 2013-10-26 13:32:54.132 12313
10001 HGFHFGHGHF 2013-10-26 18:08:32.878 6565
在这里,我想获得UserID,PostComments
每个PostID
最大值PostTransDate
。
需要输出:
--------------------------------------------------
PostID PostComments PostTransDate UserID
-----------------------------------------------------------------
10000 MJHJNGJHGH 2013-10-26 21:56:32.767 9897
10001 XCVGFDGDFG 2013-10-26 22:54:54.868 3424
我已经有得到这个的查询。
查询一:
SELECT TT.PostID,TT.PostComments,TT.UserID, TT.PostTransDate
FROM tableA TT WITH(NOLOCK)
INNER JOIN
(
SELECT PostID,MAX(PostTransDate) PostTransDate
FROM tableA T WITH(NOLOCK)
GROUP BY PostID
) T ON T.PostID = TT.PostID AND T.PostTransDate = TT.PostTransDate
查询 2:
SELECT *
FROM
(
SELECT PostID,UserID,PostTransDate,T.PostComments,
ROW_NUMBER() OVER(PARTITION BY PostID ORDER BY PostTransDate DESC) RNO
FROM tableA T
) N WHERE RNO = 1
我无法在生产环境中运行这些查询,因为这些查询非常繁重。如果有人有比这更简化的查询,请发布。