使用postgresql,如何连接表,从左表中选择全部,从右表中选择总和和计数?

时间:2015-03-23 11:00:19

标签: postgresql

我想从expense_projects(左表)中选择两个字段,并使用与左表相关的where子句计算来自expense_items(右表)的行和总金额。右表中可能没有条目对应,在这种情况下我想返回null或0。

我想实现以下目标:

project   item_count  item_spend
pr 1      19          298.54
pr 2      0           0
pr 3      2           18.73

表结构是:

CREATE TABLE expense_projects(
project_id serial NOT NULL PRIMARY KEY,
project_company_id int,
project_name text,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP NOT NULL 
);

CREATE TABLE expense_items(
item_id serial NOT NULL PRIMARY KEY,
expense_project_id int, 
expense_company_id int,
user_id int,
item text,
amount numeric(10,2),
mop text, 
card_digits text,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP NOT NULL 
);

到目前为止,我有

SELECT i.expense_project_id, p.project_id, p.project_name, SUM(amount) AS item_amount, count(item) AS item_count FROM expense_items i, expense_projects p GROUP BY i.expense_project_id, p.project_id, p.project_name

重复两个右表中条目的一个表的数据,所以我得到重复,因为左表有两个项目,但右表只有一个项目的数据。另外我不知道如何添加where子句。

用简单的英语我想:

SELECT p.project_name, p.project_id FROM expense_projects p (left table)
WHERE p.project_company_id = 2 (for example)
LEFT JOIN expense_items i ON p.project_id = i.expense_project_id
COUNT(item) AS item_count
SUM(amount) AS item_amount
GROUP BY p.project_id, p.project_name

所有人都非常感激地收到了你们,谢谢。

1 个答案:

答案 0 :(得分:0)

此查询应该执行您想要的操作。

 SELECT 
        p.project_name, 
        p.project_id,
        COUNT(i.expense_project_id) AS item_count,
        SUM(COALESCE(amount,0)) AS item_amount
 FROM expense_projects p 
 LEFT JOIN expense_items i ON p.project_id = i.expense_project_id      
 WHERE p.project_company_id = 2
 GROUP BY p.project_id, p.project_name