postgresql 从id列返回特定值以创建新列

j2datikz  于 2022-12-03  发布在  PostgreSQL
关注(0)|答案(1)|浏览(138)

我有这个示例数据来使用它

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
oalqel3c

oalqel3c1#

您需要的是一个窗口函数:

SELECT
  id_,
  product,
  sum(price) total,
  (row_number() OVER (PARTITION BY id_ ORDER BY product) = 1)::int AS tot_cust
FROM example     
GROUP BY id_, product  
ORDER BY id_, product

相关问题