【发布时间】:2022-01-14 15:38:01
【问题描述】:
所以对于以下架构:
CREATE TABLE activity (
id integer NOT NULL,
start_date date NOT NULL
);
CREATE TABLE account (
id integer NOT NULL,
name varchar NOT NULL
);
CREATE TABLE contact (
id integer NOT NULL,
account_id integer NOT NULL,
name varchar NOT NULL
);
CREATE TABLE activity_contact (
id integer NOT NULL,
contact_id integer NOT NULL,
activity_id integer NOT NULL
);
insert into activity(id, start_date)
values
(1, '2021-11-03'),
(2, '2021-10-03'),
(3, '2021-11-02');
insert into account(id, name)
values
(1, 'Test Account');
insert into contact(id, account_id, name)
values
(1, 1, 'John'),
(2, 1, 'Kevin');
insert into activity_contact(id, contact_id, activity_id)
values
(1, 1, 1),
(2, 2, 1),
(3, 2, 2),
(4, 1, 3);
您可以看到有 3 个活动,每个联系人有两个。我要搜索的是前两个月每个帐户的活动数量。所以我有以下查询
SELECT contact.account_id AS accountid,
count(*) FILTER (WHERE date_trunc('month'::text, activity.start_date) = date_trunc('month'::text, CURRENT_DATE - '1 mon'::interval)) AS last_month,
count(*) FILTER (WHERE date_trunc('month'::text, activity.start_date) = date_trunc('month'::text, CURRENT_DATE - '2 mons'::interval)) AS prev_month
FROM activity
JOIN activity_contact ON activity_contact.activity_id = activity.id
JOIN contact ON contact.id = activity_contact.contact_id
JOIN account ON contact.account_id = account.id
GROUP BY contact.account_id;
这会返回:
accountid last_month prev_month
1 3 1
但是这是不正确的。只有 3 个活动,只是每个联系人都看到活动 1。所以它对该活动计数两次。有没有办法让我只计算每个活动 id 一次,这样就不会重复?
【问题讨论】:
-
用
count(DISTINCT activity_id)替换count(*) -
很棒的东西主管。谢谢
标签: sql postgresql