试图创建一个按日期分组的报告表,但对几种不同的过滤器进行求和。
例如,假设我在一家公司中有多个地点,并且想对按日期分组的销售额进行汇总。
比如说源表
Date | Location | Amount
===========================
Mon | One | 10
Mon | Two | 15
Mon | One | 12
Tue | One | 13
Tue | Three | 17
我想将其转换为
Date | Location One Sales | Location Two Sales
================================================
Mon | 22 | 15
Tue | 13 | 0
现在我正为此绞尽脑汁,撞上墙了。
谢谢!
答案 0 :(得分:1)
您可以使用CASE
有条件地选择。
PostgreSQL 9.6模式设置:
CREATE TABLE Sales
("Date" varchar(3), "Location" varchar(5), "Amount" int)
;
INSERT INTO Sales
("Date", "Location", "Amount")
VALUES
('Mon', 'One', 10),
('Mon', 'Two', 15),
('Mon', 'One', 12),
('Tue', 'One', 13),
('Tue', 'Three', 17)
;
查询1 :
SELECT "Date"
, sum(case "Location" when 'One' then "Amount" else 0 end) as "Location One Sales"
, sum(case "Location" when 'Two' then "Amount" else 0 end) as "Location Two Sales"
FROM Sales
GROUP BY "Date"
Results :
| Date | Location One Sales | Location Two Sales |
|------|--------------------|--------------------|
| Mon | 22 | 15 |
| Tue | 13 | 0 |
答案 1 :(得分:1)
提供此数据:
CREATE TABLE sales (
id SERIAL PRIMARY KEY,
date TEXT,
location TEXT,
amount INT
);
INSERT INTO sales (date, location, amount) VALUES
('Mon', 'One', 10),
('Mon', 'Two', 15),
('Mon', 'One', 12),
('Tue', 'One', 13),
('Tue', 'Thr', 17)
;
您可以手动构建列,如下所示:
SELECT
date,
SUM(CASE WHEN location='One' THEN amount ELSE 0 END) AS loc_one,
SUM(CASE WHEN location='Two' THEN amount ELSE 0 END) AS loc_two
FROM
sales
GROUP BY date
ORDER BY date;
但也许更健壮的解决方案是在两个字段上使用分组方式。
SELECT
date,
location,
SUM(amount)
FROM
sales
GROUP BY date, location
ORDER BY date, location;
SQLFiddle:http://www.sqlfiddle.com/#!17/7417e/9