我想要完成的是查询前2个购买的产品和至少2个购买的产品以及product_id,但必须包含已购买相同次数的产品。
这是我使用
的表格CREATE TABLE Orderlines(
ORDERLINEID serial NOT NULL,
ORDERID integer NOT NULL,
PROD_ID integer NOT NULL,
QUANTITY text NOT NULL,
ORDERDATE date NOT NULL,
PRIMARY KEY(ORDERLINEID,ORDERID)
);
这是半成品查询,按照他们购买的时间对产品进行分类,包括他们的prod_id。
SELECT PROD_ID, COUNT(*) AS c
FROM Orderlines
GROUP BY Orderlines.PROD_ID
ORDER BY c DESC;
答案 0 :(得分:2)
一种方法是使用dense_rank()
:
SELECT PROD_ID, c
FROM (SELECT PROD_ID, COUNT(*) AS c,
DENSE_RANK() OVER (ORDER BY COUNT(*) ASC) as seqnum_asc,
DENSE_RANK() OVER (ORDER BY COUNT(*) DESC) as seqnum_desc
FROM Orderlines
GROUP BY Orderlines.PROD_ID
) o
WHERE seqnum_asc <= 2 OR
seqnum_desc <= 2
ORDER BY c DESC;