使用postgresql在交叉表中的和值无效

时间:2017-11-08 17:48:29

标签: postgresql crosstab

我必须开发一个包含员工工作细节并留下详细信息的交叉表报告

表格

  

员工表

 
employeeid      workdate       doctorvisit
   E001        2017/07/03        Doc10
   E002        2017/07/04        Doc15
   E003        2017/07/28        Doc13
   E003        2017/07/28        Doc16
  

离开表

employeeid     leavedate       leavetype
   E001        2017/07/12      casualleave
   E002        2017/07/20      sickleave
   E003        2017/07/27      casualleave
  

查询


    select * from crosstab(
        $$with cte as(
    select distinct emp.employeeid as id,emp.workdate as dates,count(doctorvisit) as ct from employee emp
    group by emp.employeeid,emp.startdate
    union all
    select distinct lea.employeeid as id,lea.leavedate as dates,case when lea.leavetype = 'casualleave' then 999 when lea.leavetype='sickleave' then 998 else null end as ct from leave lea
    group by lea.employeeid,lea.leavedate,lea.leavetype)
    table cte
    union all
    select id,'totalvisit' as dates,case when ct = 999 then null when ct = 998 then null else sum(ct)end as ct from cte
    group by cte.id,cte.ct
    order by dates$$,
    $$SELECT unnest('{2017-07-03,2017-07-04,2017-07-12,2017-07-20,2017-07-27,2017-07-28,totalvisit}'::text[])$$
    )AS t(
    claimid text,
    "2017-07-03" text,"2017-07-04" text,"2017-07-12" text,"2017-07-20" text,"2017-07-27" text,"2017-07-28" text,totalvisit text)

当我执行此查询时,我得到了像

这样的输出
2017-07-03 2017-07-04 2017-07-12 2017-07-20 2017-07-27 2017-07-28  totalvisit 
    1          1         999         998      999          2           2

所以这里sum(ct)作为无效计数totalvisit为4但显示2

  

预期输出

2017-07-03 2017-07-04 2017-07-12 2017-07-20 2017-07-27 2017-07-28  totalvisit 
    1          1         999         998      999          2           4

请帮我这个

非常感谢

1 个答案:

答案 0 :(得分:0)

为此你可以先计算总和(ct)然后你可以联合离开表如下

SELECT id,
       'totalvisit' AS dates,
       CASE
           WHEN ct = 999 THEN NULL
           WHEN ct = 998 THEN NULL
           ELSE sum(ct)
       END AS ct
FROM cte
UNION ALL
SELECT DISTINCT lea.employeeid AS id,
                lea.leavedate AS dates,
                CASE
                    WHEN lea.leavetype = 'casualleave' THEN 999
                    WHEN lea.leavetype='sickleave' THEN 998
                    ELSE NULL
                END AS ct
FROM leave lea
GROUP BY lea.employeeid,
         lea.leavedate,
         lea.leavetype)

现在你得到你期望的结果