我正在建立一个查询,该查询旨在显示每月两个日期变量的出现次数。我能够组合两个独立的查询:我计算每月的出现次数和组数,但是我不知道如何将这两个查询联接在一起,因为它们来自同一张表,并且仍然只显示一列的一个月。
谢谢大家的帮助!
格式:YYYY-MM-DD
|---------------------|------------------| | onboard_date | offboard_date | |---------------------|------------------| | 2019/01/15 | - | |---------------------|------------------| | 2019/01/25 | 2019/02/15 | |---------------------|------------------| | 2019/02/13 | 2019/02/20 | |---------------------|------------------| | 2019/02/18 | - | |---------------------|------------------| | 2019/03/09 | - | |---------------------|------------------|
我尝试过的工作:
SELECT DATE_TRUNC('month', onboard_date) AS onboard_month,
COUNT(*) as onboards
FROM lukla.trn_users trn
WHERE trn.company_name = 'amaro'
GROUP BY DATE_TRUNC('month', onboard_date)
ORDER BY DATE_TRUNC('month', onboard_date)
和
SELECT DATE_TRUNC('month', offboard_date) AS onboard_month,
COUNT(*) as onboards
FROM lukla.trn_users trn
WHERE trn.company_name = 'amaro' AND offboard_date IS NOT NULL
GROUP BY DATE_TRUNC('month', offboard_date)
ORDER BY DATE_TRUNC('month', offboard_date)
我想要的结果:
|--------------|------------|------------| | month | onboards | offboards | |--------------|------------|------------| | 01 | 2 | 0 | |--------------|------------|------------| | 02 | 2 | 2 | |--------------|------------|------------| | 03 | 1 | 0 | |--------------|------------|------------|
答案 0 :(得分:2)
横向联接使这一过程变得非常简单:
select date_trunc('month', v.dte) as month, sum(v.is_onboard) as onboards, sum(v.is_offboard) as offboards
from trn_users t cross join lateral
(values (t.onboard_date, (t.onboard_date is not null)::int, 0),
(t.offboard_date, 0, (t.offboard_date is not null)::int)
) v(dte, is_onboard, is_offboard)
where v.dte is not null
group by month
order by month;
Here是db <>小提琴。
答案 1 :(得分:0)
您可以尝试完全连接两个派生表,一个派生表的数量,另一个派生表的数量。
SELECT coalesce(x.month, y.month) month,
coalesce(x.count, 0) onboards,
coalesce(y.count, 0) offboards
(SELECT date_trunc('month', trn.onboard_date) month
count(*) count
FROM lukla.trn_users trn
WHERE trn.company_name = 'amaro'
AND trn.onboard_date IS NOT NULL
GROUP BY date_trunc('month', trn.onboard_date)) x
FULL JOIN (SELECT date_trunc('month', trn.offboard_date) month
count(*) count
FROM lukla.trn_users trn
WHERE trn.company_name = 'amaro'
AND trn.offboard_date IS NOT NULL
GROUP BY date_trunc('month', trn.offboard_date)) y
ON y.month = x.month
ORDER BY coalesce(x.month, y.month);