将两列相乘并在新列PostreSQL中显示结果

时间:2019-03-21 13:58:33

标签: sql postgresql

我有一个超过10000行的CSV文件。我想将两列(数量和单价)相乘,并在新列中显示结果(我的表中没有该列-列名可以为“总计”)。我还需要计算每个客户花费了多少。我写了一个代码,但出现此错误:

ERROR: integer out of range
SQL state: 22003

这是代码:

CREATE TABLE public."My_OnlineRetail"(invoiceno varchar(100),
                                        stockcode varchar(100),
                                        description varchar(100),
                                        quantity integer,
                                        invoicedate timestamp,
                                        unitprice float,
                                        currency varchar(10),
                                        customerid integer,
                                        country varchar(100));

SELECT * FROM public."My_OnlineRetail";
COPY public."My_OnlineRetail" FROM 'C:\Users\Jasmina\Desktop\OnlineRetail2NEW.csv' DELIMITER ',' CSV HEADER;

/*SELECT DISTINCT customerid FROM public."My_OnlineRetail";*/

SELECT customerid, quantity, unitprice, (quantity * quantity) FROM public."My_OnlineRetail";

我知道在此之后,我需要遍历每个客户并求和总列,但是我不知道该怎么做。

1 个答案:

答案 0 :(得分:1)

我想你想要

SELECT customerid, SUM(quantity*unitprice) as total
FROM public."My_OnlineRetail"
GROUP BY customerid;

如果您遇到范围问题,请切换为数字:

SELECT customerid, SUM( (quantity::numeric) * (unitprice::numeric) ) as total
FROM public."My_OnlineRetail"
GROUP BY customerid;

最后的结果:

SELECT customerid, SUM( (quantity::numeric) * (unitprice::numeric) )::numeric(15, 2) as total
FROM public."My_OnlineRetail"
GROUP BY customerid;