我在PostgreSQL中进行此查询时遇到了麻烦。我按分组进行,它给了我适当的结果,但是我找不到我真正想要的具体解决方案。已返回两列。但是我想要此结果的total_amount的总和并仅返回一列
SELECT pi.user_id,
Sum(total_amount) AS total_amount,
emp_id,
status,
max_pi_pending_amount,
first_pending_pi_warning_percentage,
second_pending_pi_warning_percentage,
emp_id,
Coalesce(pending_pi_amount, 0) AS pending_pi_amount
FROM proforma_invoice pi
JOIN users usr
ON pi.user_id = usr.user_id
JOIN employee emp
ON usr.employee_id = emp.emp_id
JOIN alarm_parameter ap
ON pi.user_id = ap.user_id
WHERE pi.user_id = 18
AND (status = 'Created'
OR status = 'Approved')
GROUP BY pi.user_id,
status,
max_pi_pending_amount,
first_pending_pi_warning_percentage,
second_pending_pi_warning_percentage,
emp_id,
pending_pi_amount
答案 0 :(得分:1)
只需将状态列从查询中删除,因为如果将它们组合在一起,则该列无效
DetailView
答案 1 :(得分:0)
在我看来您需要子查询或cte
with cte as
(
SELECT pi.user_id,
Sum(total_amount) AS total_amount,
emp_id,
status,
max_pi_pending_amount,
first_pending_pi_warning_percentage,
second_pending_pi_warning_percentage,
emp_id,
Coalesce(pending_pi_amount, 0) AS pending_pi_amount
FROM proforma_invoice pi
JOIN users usr
ON pi.user_id = usr.user_id
JOIN employee emp
ON usr.employee_id = emp.emp_id
JOIN alarm_parameter ap
ON pi.user_id = ap.user_id
WHERE pi.user_id = 18
AND (status = 'Created'
OR status = 'Approved')
GROUP BY pi.user_id,
status,
max_pi_pending_amount,
first_pending_pi_warning_percentage,
second_pending_pi_warning_percentage,
emp_id,
pending_pi_amount
) select user_id,sum(total_amount) from cte group by user_id