带连接和 PostgreSQL 的二维 table 查询
2 dimensional table query with join and PostgreSQL
尝试从 SQL 查询 (Postgres) return 二维 table。阅读 Pivot Table(但不确定它是否对加入有效)和 crosstab/tablefunc 但运气不好。
预期结果
App A | App B
2020-01-01 8 | 2
2020-02-01 14 | 5
2020-03-01 13 | 0
我有 2 个 table:
- 应用程序:名称
- 订单:日期,...
我希望按月和应用程序计算订单。
到目前为止我的尝试。
SELECT date_trunc('month', date) as date, count(1), x.name
FROM (SELECT date_trunc('month', date) as date, application_id
FROM orders
GROUP BY date, application_id) o
JOIN applications x ON o.application_id = x.id AND x.id in (1, 2, 5)
WHERE
o.date > NOW() - '9 months'::interval
group by date, x.name
order by date, x.name
其中return
date count name
2020-01-01 8 App A
2020-01-01 2 App B
2020-02-01 14 App A
2020-02-01 5 App B
谢谢。
要将结果集转向固定的值列表,您可以进行条件聚合:
select date_trunc('month', o.date) date,
count(*) filter(where a.name = 'App A') app_a,
count(*) filter(where a.name = 'App B') app_b
from applications a
inner join orders o on o.application_id = a.id
where o.date > date_trunc('month', current_date) - '9 months'::interval
group by 1
order by 1
请注意,我修改了 where
子句,使其过滤整个月。
尝试从 SQL 查询 (Postgres) return 二维 table。阅读 Pivot Table(但不确定它是否对加入有效)和 crosstab/tablefunc 但运气不好。
预期结果
App A | App B
2020-01-01 8 | 2
2020-02-01 14 | 5
2020-03-01 13 | 0
我有 2 个 table:
- 应用程序:名称
- 订单:日期,...
我希望按月和应用程序计算订单。
到目前为止我的尝试。
SELECT date_trunc('month', date) as date, count(1), x.name
FROM (SELECT date_trunc('month', date) as date, application_id
FROM orders
GROUP BY date, application_id) o
JOIN applications x ON o.application_id = x.id AND x.id in (1, 2, 5)
WHERE
o.date > NOW() - '9 months'::interval
group by date, x.name
order by date, x.name
其中return
date count name
2020-01-01 8 App A
2020-01-01 2 App B
2020-02-01 14 App A
2020-02-01 5 App B
谢谢。
要将结果集转向固定的值列表,您可以进行条件聚合:
select date_trunc('month', o.date) date,
count(*) filter(where a.name = 'App A') app_a,
count(*) filter(where a.name = 'App B') app_b
from applications a
inner join orders o on o.application_id = a.id
where o.date > date_trunc('month', current_date) - '9 months'::interval
group by 1
order by 1
请注意,我修改了 where
子句,使其过滤整个月。