获取特定产品号的金额 = 0 且版本号 = 最高的产品
SELECT ProductNo, MAX(VersionNo) as VersionNo
FROM Products
WHERE Amount = 0
GROUP BY ProductNo
HAVING MAX(VersionNo) = (SELECT MAX(VersionNo) FROM Products WHERE ProductNo = Products.ProductNo)
我期待着
产品编号 | 版本号 | 金额 |
---|---|---|
10 | 3 | 0 |
30 | 2 | 0 |
您可以利用分析查询,即带有 max 的 over 子句来获得所需的结果。
-- Create the test table
CREATE TABLE test (
ProductNo INTEGER NOT NULL,
VersionNo INTEGER NOT NULL,
Amount NUMERIC
);
-- Insert data into the test table
INSERT INTO test (ProductNo, VersionNo, Amount) VALUES
(10, 1, 100),
(10, 2, 120),
(10, 3, 0),
(20, 1, 45),
(20, 2, 0),
(20, 3, 55),
(20, 4, 78),
(30, 1, 120),
(30, 2, 0);
with CTE1 AS
(
select productno, versionno, max(versionno) over(partition by productno) max_versionno, amount
from test)
select productno, versionno, amount from cte1 where amount = 0 and versionno = max_versionno;