从分组结果中获取整行

时间:2011-10-27 02:02:53

标签: sql sql-server database

这是一个示例数据库表:

| ID | ProductID | DateChanged | Price
| 1  | 12        | 2011-11-11  |  93
| 2  | 2         | 2011-11-12  |  12
| 3  | 3         | 2011-11-13  |  25
| 4  | 4         | 2011-11-14  |  17
| 5  | 12        | 2011-11-15  |  97

基本上,我想要的是获得按ProductID分组的最新价格。

结果应该是这样的:

| ID | ProductID | Price 
| 2  | 2         |  12
| 3  | 3         |  25
| 4  | 4         |  17
| 5  | 12        |  97

如果您注意到,第一行不存在,因为ProductID 12的新价格是ID 5的行。

基本上,它应该像获取ID,产品ID和按产品ID分类的价格,其中DateChanged是最新的。

4 个答案:

答案 0 :(得分:2)

SELECT ID, ProductId, Price
FROM
(
   SELECT ID, ProductId, Price
      , ROW_NUMBER() OVER (PARTITION BY ProductID ORDER BY DateChanged DESC) AS rowNumber
   FROM yourTable
) AS t
WHERE t.rowNumber = 1

答案 1 :(得分:1)

SELECT  ID, ProductID,DateChanged, Price
FROM    myTable  
WHERE   ID IN
(
    SELECT  MAX(ID)
    FROM    myTable 
    GROUP BY ProductID
)

答案 2 :(得分:0)

select a.id, a.productid, a.price
from mytable a,
    (select productid, max(datechanged) as maxdatechanged
    from mytable
    group by productid) as b
where a.productid = b.productid and a.datechanged = b.maxdatechanged

答案 3 :(得分:0)

SELECT ID, ProductId, Price 
from myTable A
where DateChanged >= all 
  (select DateChanged
   from myTable B
   where B.ID = A.ID);