我有这个示例数据来使用它
CREATE TABLE example (
id_ TEXT ,
product TEXT ,
price numeric (10));
INSERT INTO example (id_, product, price)
values
('1a','Soap', 200),
('1a','Conditioner', 300),
('1a','Shampoo', 250),
('1a','Soap', 100),
('2a','Toothbrush', 150),
('2a','Soap', 200),
('2a','Mouthwash',350),
('3a','Shampoo',250),
('3a','Perfume',400);
通常情况下,大多数人都将使用此代码
SELECT id_, product, sum(price)total
FROM example
group by id_, product
order by id_, product;
所以它会得到这样的输出
id_ product total
1a Conditioner 300
1a Shampoo 250
1a Soap 300
2a Mouthwash 350
2a Soap 200
2a Toothbrush 150
3a Perfume 400
3a Shampoo 250
有没有什么方法可以让它像这样,也许用例可以让它变得简单?
如果id_不同,则给予1,如果id_相同,则给出0,
id_ product total tot_cust
1a Conditioner 300 1
1a Shampoo 250 0
1a Soap 300 0
2a Mouthwash 350 1
2a Soap 200 0
2a Toothbrush 150 0
3a Perfume 400 1
3a Shampoo 250 0
1条答案
按热度按时间oalqel3c1#
您需要的是一个窗口函数: