SQL select 使用带聚合计数的联接查询
SQL select query using Joins with aggregate counts
我有一个包含以下字段的 table:
tickets: id, createddate, resolutiondate
样本数据集有:
jira=# select * from tickets;
id | createddate | resolutiondate
---------+-------------+----------------
ticket1 | 2020-09-21 | 2020-10-01
ticket2 | 2020-09-22 | 2020-09-23
ticket3 | 2020-10-01 |
ticket4 | 2020-10-01 | 2020-10-04
ticket5 | 2020-10-01 |
ticket6 | 2020-10-01 | 2020-10-07
(6 rows)
jira=#
我想创建一个报告的查询:
Week: Issues Created: Issues Resolved
我可以进行两个单独的查询:
# select date_trunc('week', createddate) week, count(id) created
from tickets
group by week
order by week desc
;
week | created
------------------------+---------
2020-09-28 00:00:00+00 | 4
2020-09-21 00:00:00+00 | 2
(2 rows)
# select date_trunc('week', resolutiondate) week, count(id) resolved
from tickets
where resolutiondate is not NULL
group by week
order by week desc
;
week | resolved
------------------------+----------
2020-10-05 00:00:00+00 | 1
2020-09-28 00:00:00+00 | 2
2020-09-21 00:00:00+00 | 1
(3 rows)
但是 - 我不知道如何(使用连接、联合、子查询……?)将这些查询组合成具有适当聚合的组合查询。
我正在做的是 Postgres - 任何指点将不胜感激。
在聚合值之前执行合并在这里可能有效,例如
select week,
count(id_created) as created,
count(id_resolved) as resolved
from (
select date_trunc('week', resolutiondate) week, NULL as id_created, id as id_resolved from tickets UNION ALL
select date_trunc('week', createddate) week, id as id_created, NULL as id_resolved from tickets
) t
group by week
order by week desc
让我知道这是否适合你。
我有一个包含以下字段的 table:
tickets: id, createddate, resolutiondate
样本数据集有:
jira=# select * from tickets;
id | createddate | resolutiondate
---------+-------------+----------------
ticket1 | 2020-09-21 | 2020-10-01
ticket2 | 2020-09-22 | 2020-09-23
ticket3 | 2020-10-01 |
ticket4 | 2020-10-01 | 2020-10-04
ticket5 | 2020-10-01 |
ticket6 | 2020-10-01 | 2020-10-07
(6 rows)
jira=#
我想创建一个报告的查询:
Week: Issues Created: Issues Resolved
我可以进行两个单独的查询:
# select date_trunc('week', createddate) week, count(id) created
from tickets
group by week
order by week desc
;
week | created
------------------------+---------
2020-09-28 00:00:00+00 | 4
2020-09-21 00:00:00+00 | 2
(2 rows)
# select date_trunc('week', resolutiondate) week, count(id) resolved
from tickets
where resolutiondate is not NULL
group by week
order by week desc
;
week | resolved
------------------------+----------
2020-10-05 00:00:00+00 | 1
2020-09-28 00:00:00+00 | 2
2020-09-21 00:00:00+00 | 1
(3 rows)
但是 - 我不知道如何(使用连接、联合、子查询……?)将这些查询组合成具有适当聚合的组合查询。
我正在做的是 Postgres - 任何指点将不胜感激。
在聚合值之前执行合并在这里可能有效,例如
select week,
count(id_created) as created,
count(id_resolved) as resolved
from (
select date_trunc('week', resolutiondate) week, NULL as id_created, id as id_resolved from tickets UNION ALL
select date_trunc('week', createddate) week, id as id_created, NULL as id_resolved from tickets
) t
group by week
order by week desc
让我知道这是否适合你。