嘿,我有点坚持这个查询。使用SQL-server
我在表格中有UNIQUE(date,medId,userId)
我有这张桌子
date | medId | userId | Quantity
2016-06-10 | 2 | 1 | 28
2016-06-07 | 1 | 1 | 19
2016-06-06 | 1 | 1 | 10
在这种情况下,我希望得到每组medId,userId的最大日期行 我会得到
2016-06-10 | 2 | 1 | 28
2016-06-07 | 1 | 1 | 19
提前感谢!
我试过这个
SELECT
a.userMedStockDate,
a.userMedStockMedId,
a.userMedStockUserId,
a.userMedStockQuantity
FROM (SELECT
MAX(userMedStockDate) AS userMedStockDate,
userMedStockQuantity,
userMedStockUserId,
userMedStockMedId,
ROW_NUMBER() OVER (partition by userMedStockMedId,userMedStockUserId
ORDER BY MAX(userMedStockDate) desc) AS rnk
FROM UserMedStock
GROUP BY
userMedStockUserId,
userMedStockQuantity,
userMedStockMedId) a
WHERE a.rnk = 1
[解决]
答案 0 :(得分:1)
这应该有效
select * from
(
select
[date] , medId, userId ,Quantity
,row_number() over (partition by medId, userId order by [date] desc) as rowid
from yourtable
) as x
where rowid = 1
答案 1 :(得分:0)
也可以试试这个:
select y.* from
table1 y inner join
(
SELECT [Date] = MAX([Date]), medId, userId
FROM table1
GROUP BY medId, userId
) x on y.[Date] = x.[Date] and y.medId = x.medId and y.userId = x.userId
答案 2 :(得分:0)
我将字段更改为我的实际表格,但这里
IIS