GROUP BY正在创建多行而不是1

时间:2015-03-24 20:34:04

标签: postgresql group-by

这是在Postgresql 8.2中我创建了以下视图,并希望结果由“员工”字段组合在一起:

CREATE OR REPLACE VIEW stg.vw_dw_employees AS 
SELECT zvpa0001.pernr AS employee, 
CASE
WHEN zvpa0105.usrty::text = '0001'::text 
THEN max(zvpa0105.usrid::text)
ELSE NULL::text
END AS login, 
CASE
WHEN zvpa0001.sname IS NULL THEN              
max(upper(zvpa0001.ename::text))::character varying
ELSE zvpa0001.sname
END AS employee_name, 
CASE
WHEN zvpa0105.usrty::text = '0015'::text 
THEN max(zvpa0105.usrid::text)
ELSE NULL::text
END AS gid, 
CASE
WHEN zvpa0105.usrty::text = '0012'::text 
THEN max(zvpa0105.usrid::text)
ELSE NULL::text
END AS webkey
FROM src.zvpa0001
LEFT JOIN src.zvpa0105 
ON zvpa0001.pernr = zvpa0105.pernr
GROUP BY zvpa0001.pernr, zvpa0105.usrty, zvpa0001.sname, zvpa0001.persg;

当我查询视图时,我看到同一个员工有多行。 Example

我已经厌倦了几个解决方法(加入子查询)但无法产生所需的结果。任何帮助将不胜感激。

3 个答案:

答案 0 :(得分:0)

分组在所有情况下都不创建一行,这意味着根据您为组功能选择的字段,员工34被分组多次。

尝试推断查询背后的逻辑

答案 1 :(得分:0)

  

希望结果由'员工'组合在一起。字段:

然后实际执行此操作:GROUP BY employee

SELECT z1.pernr AS employee
     , CASE WHEN mine(z5.usrty::text) = '0001'
        THEN max(z5.usrid::text) END AS login
     , CASE WHEN min(z1.sname) IS NULL
        THEN max(upper(z1.ename::text))
        ELSE z1.sname END AS employee_name
     , CASE WHEN min(z5.usrty)::text = '0015'
        THEN max(z5.usrid::text) END AS gid
     , CASE WHEN min(z5.usrty)::text = '0012
        THEN max(z5.usrid::text) END AS webkey
FROM   src.zvpa0001      z1
LEFT   JOIN src.zvpa0105 z5 USING(pernr)
GROUP  BY employee;

所有其他列都需要成为聚合函数的一部分。

我删除了一些噪音,但查询可能并不理想。你的演员是可疑的。如果z1.pernr是主键,您可以简化更多。但缺少基本信息。

答案 2 :(得分:0)

感谢您的建议。我想通了。 SELECT DISTINCT ON()完成了这个伎俩。