选择SQL Server中所有销售的最新产品

时间:2013-01-16 23:03:38

标签: sql sql-server

我在SQL Server中有这个项目表。

ID_Item   | ID_Sale  | ID_Product |
1         | 200      | 2314       |
2         | 200      | 3894       |
3         | 200      | 4949       |
4         | 100      | 9389       |
5         | 100      | 9499       |
6         | 300      | 9388       |

我需要获得最后一张唱片,记录......

ID_Item   | ID_Sale  | ID_Product |
3         | 200      | 4949       |
5         | 100      | 9499       |
6         | 300      | 9388       |

我尝试使用此代码,但只搜索一条记录

Select Top 1 * From Itens 
Where ID_Sale = 200
Order by ID_Item Desc

在整个表格中获取我需要的结果的消息?

由于

2 个答案:

答案 0 :(得分:1)

SELECT ID_Item, ID_Sale, ID_Product 
FROM Tbl
WHERE Id_Item IN
         (
             SELECT Max(Id_Item) Id
             FROM Tbl
             WHERE [DateTime] BETWEEN @StartDate AND @EndDate
             GROUP BY Id_Sale
          )

如果您使用SQL SERVER 2005 +

;WITH CTE
AS
(
   SELECT ID_Item, ID_Sale, ID_Product, ROW_NOUMBER() OVER (PARTITION BY ID_Sale ORDER BY ID_Item DESC) RN
   FROM Tbl
   WHERE [DateTime] BETWEEN @StartDate AND @EndDate
)
SELECT ID_Item, ID_Sale, ID_Product
FROM CTE
WHERE RN = 1

答案 1 :(得分:0)

哟可以简单地使用此查询

    select * from Item where ID_Item in(
select MAX(ID_Item) as ID_Item from Item group by ID_Sale)