我try 从下表在Postgres中创建一个Pivot表
Product_info表
SQL个
CREATE TABLE product_info (
ID varchar(10),
date VARCHAR(20) NOT NULL,
product VARCHAR(20) NOT NULL,
product_cost integer
);
INSERT INTO
product_info(ID, date, product, product_cost)
VALUES
('1', 'AUG-23','Laptop',100),
('1', 'AUG-23','Phone',80),
('1', 'AUG-23','Keypad',50),
('1', 'SEP-23','Laptop',200),
('1', 'SEP-23','Phone',100),
('1', 'SEP-23','Ipad',150),
('1', 'SEP-23','Keypad',80),
('2', 'AUG-23','Laptop',100),
('2', 'AUG-23','Phone',90),
('2', 'AUG-23','Keypad',70),
('2', 'SEP-23','Laptop',120),
('2', 'SEP-23','Phone',30),
('2', 'SEP-23','Ipad',80),
('2', 'SEP-23','Keypad',40);
Tried below PIVOT Query个
SELECT * FROM crosstab(
'SELECT date, id,product, sum(product_cost)
FROM product_info
GROUP BY 1, 2,3
ORDER BY 1, 2,3'
,
'SELECT DISTINCT product FROM product_info ORDER BY 1'
) as cte(
date text,
id text,
"Ipad" numeric,
"Keypad" numeric,
"Laptop" numeric,
"Phone" numeric
)
RETURNED RESULT个
date | id | Ipad | Keypad | Laptop | Phone |
---|---|---|---|---|---|
AUG-23 | 1 | NULL | 70 | 100 | 90 |
SEP-23 | 1 | 80 | 40 | 120 | 30 |
EXPECTED RESULT个
id | date | Ipad | Keypad | Laptop | Phone |
---|---|---|---|---|---|
1 | AUG-23 | NULL | 50 | 100 | 80 |
2 | AUG-23 | NULL | 70 | 100 | 90 |
1 | SEP-23 | 150 | 80 | 200 | 100 |
2 | SEP-23 | 80 | 40 | 120 | 30 |
返回的实际上是ID=‘2’的返回值 当两个ID都需要时