获取特定产品的
amount=0
和 versionno=highest
的产品:
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;
正确使用别名可以解决这个问题:
SELECT p1.ProductNo, MAX(p1.VersionNo) as VersionNo
FROM Products p1
WHERE p1.Amount = 0
GROUP BY ProductNo
HAVING MAX(p1.VersionNo) = (SELECT MAX(p2.VersionNo) FROM Products p2 WHERE p2.ProductNo = p1.ProductNo)
参见:DBFIDDLE