我有此表结构和示例数据。此表中有销售订单的迭代。最初,要求鼠标15 Qty
。后来买方决定更新Qty
并将其设置为25,然后再次意识到他只需要20。因此,我想从销售订单中获取特定商品的最新行。
CREATE TABLE SaleOrder
(
ID INT PRIMARY KEY,
Item VARCHAR(25),
Qty INT
)
INSERT INTO SaleOrder VALUES (1, 'Mouse', 15);
INSERT INTO SaleOrder VALUES (2, 'Key Board', 10);
INSERT INTO SaleOrder VALUES (3, 'Printer', 3);
INSERT INTO SaleOrder VALUES (4, 'Mouse', 25);
INSERT INTO SaleOrder VALUES (5, 'Mouse', 20);
这是我写的查询。
SELECT ID, Item, Qty
FROM SaleOrder M
WHERE ID = (SELECT MAX(ID) FROM SaleOrder S WHERE S.ID = M.ID GROUP BY Item)
预期的输出结果应该包含3行。
ID Item Qty
1 Mouse 15
2 Key Board 10
3 Printer 3
4 Mouse 25
5 Mouse 20
我这里缺少什么吗?
答案 0 :(得分:3)
您可以尝试使用ROW_NUMBER
窗口函数来使每个Item
最多获得一个
SELECT ID,Item,Qty
FROM (
SELECT *,ROW_NUMBER() OVER(PARTITION BY Item ORDER BY ID DESC) rn
FROM SaleOrder
) t1
where rn = 1
答案 1 :(得分:3)
您可以使用以下两种方法之一:
使用SQL> create table test (col varchar2(10));
Table created.
SQL> insert into test values ('abc');
1 row created.
SQL> select length(col) from test;
LENGTH(COL)
-----------
3
SQL> insert into test values (rpad('def', 10, ' '));
1 row created.
SQL> select col, length(col) len from test;
COL LEN
---------- ----------
abc 3
def 10
SQL>
ROW_NUMBER()
使用子查询
;WITH CTE
AS
(
SELECT
RN = ROW_NUMBER() OVER(PARTITION BY Item ORDER BY Id DESC),
*
FROM SaleOrder
)
SELECT
*
FROM CTE
WHERE RN = 1
结果
SELECT
*
FROM SaleOrder SO
WHERE ID = (
SELECT MAX(ID) FROM SaleOrder WHERE Item = SO.Item
)-- You Don't Need the Group By Here
答案 2 :(得分:1)
您可以使用MAX
尝试以下查询。
SELECT SaleOrder.* FROM (
SELECT MAX(Id) as Id, Item FROM SaleOrder Group By Item
)a INNER JOIN SaleOrder ON a.Id = SaleOrder.Id
或者您也可以使用以下
SELECT *
FROM SaleOrder D
WHERE Id = (SELECT MAX(Id) FROM SaleOrder WHERE Item = D.Item)
两种情况下的输出如下所示
ID Item Qty
--------------------
3 Printer 3
5 Mouse 20
2 Key Board 10
您可以在此处查看演示-Group By Max Demo