表销售:
create table sales (
Date date,
customer_id integer,
product_id integer,
units_sold integer,
paid_amount integer
);
Insert into sales (Date, customer_id, product_id, units_sold, paid_amount)
VALUES
('2016-01-01', '1', '1', '5', '45'),
('2016-01-01', '2', '1', '2', '18'),
('2016-01-01', '3', '2', '7', '35'),
('2016-01-07', '1', '3', '3', '45'),
('2016-01-07', '2', '2', '5', '25'),
('2016-01-07', '4', '2', '5', '25'),
('2016-01-10', '1', '4', '5', '30'),
('2016-01-10', '2', '4', '5', '30'),
('2016-01-10', '4', '5', '6', '60'),
('2016-01-10', '4', '3', '9', '135'),
('2016-01-14', '3', '1', '4', '60'),
('2016-01-14', '2', '3', '6', '90'),
('2016-01-14', '2', '3', '6', '90');
每天显示次数最多的产品?
我正在尝试这个查询:但是我没有得到日期的结果第14天剩下的日期没事。
SELECT *
FROM (
SELECT
date,
customer_id,
product_id,
paid_amount,
rank() OVER (
PARTITION BY date
ORDER BY paid_amount
DESC
)
FROM sales) s
WHERE rank = 2;
答案 0 :(得分:0)
根据vkp:
SELECT *
FROM (
SELECT
date,
customer_id,
product_id,
paid_amount,
dense_rank() OVER (
PARTITION BY date
ORDER BY paid_amount
DESC
)
FROM sales) s
WHERE rank = 2;
对于上下文,想象一下值列表,rank和dense_rank命令desc:
Value Rank() Dense_Rank()
100 1 1
90 2 2
90 2 2
80 4 3
70 5 4
答案 1 :(得分:0)
SELECT DISTINCT
date,
nth_value(paid_amount, 2)
OVER (PARTITION BY date
ORDER BY paid_amount
ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING
) "2nd value"
FROM sales
ORDER BY date;
┌────────────┬───────────┐
│ date │ 2nd value │
├────────────┼───────────┤
│ 2016-01-01 │ 35 │
│ 2016-01-07 │ 25 │
│ 2016-01-10 │ 30 │
│ 2016-01-14 │ 90 │
└────────────┴───────────┘
(4 rows)