2016-06-07 51 views
2

嘿,我有點卡在這個查詢。使用SQL服務器根據聚合獲得最新的日期行

我有表,UNIQUE(日期,medId,用戶id)

我有這個表

date  | medId | userId | Quantity 
2016-06-10 | 2 | 1 | 28 
2016-06-07 | 1 | 1 | 19 
2016-06-06 | 1 | 1 | 10 

我想用最大日行,每組medId,用戶id的,在這種情況下 我會得到

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 

[解決]

回答

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 
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 
+0

不起作用,但謝謝 – franmcod

0

我改變了字段我的實際表格,但在這裏

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