我需要动态更改GROUP BY子句规则以进行分组。 始终返回相同的列数和名称。
例如在表格中:
CREATE TABLE employees
(
employee_id NOT NULL,
department_id integer,
status character varying(50), /*active/inactive*/
cost numeric,
income (numeric),
first_name character varying(50),
last_name character varying(50)
)
我需要查询这样的内容:
select
count(employee_id) as contacts,
sum(cost) as cost,
sum(income)/count(employee_id) as average_salary
from
employees
group by
case
when status = 'active' then /*group by*/ department_id, employee_id
when status = 'inactive' then /*group by*/ employee_id
end;
我如何运行此查询?
答案 0 :(得分:2)
这取决于你想要实现的目标:你可以在任何表达式上使用GROUP BY
,而不仅仅是在列上。
如果您想将非活动员工和所有部门的员工彼此分开,您可以使用下面的变体:
-- ...
GROUP BY CASE
WHEN status = 'active' THEN department_id
WHEN status = 'inactive' THEN NULL
END,
employee_id
但上述解决方案会将所有未分配给部门的所有其他员工(department_id IS NULL
)累积起来。如果这与您无关,这是最简单的解决方案。
您也可以使用row constructors:
-- ...
GROUP BY CASE
WHEN status = 'active' THEN ROW(department_id, employee_id)
WHEN status = 'inactive' THEN ROW(employee_id)
END
但请注意their comparison如何运作。
注意:当您在employee_id
中使用GROUP BY
时,COUNT(employee_id)
始终为1
。