汇总列并将值计数为行

时间:2019-08-13 07:49:18

标签: postgresql

我的查询输出如下:

ID      ID2      Working Leave  Off Day
14595   76885302    10     0       0
178489  78756208    0      0       1
178489  78756208    0      1       0

我想收到如下输出:

ID      ID2          code    value 
14595   76885302    Working    10     
178489  78756208    Off day    1      
178489  78756208    Leave      1      

我的查询如下:

select tei.organisationunitid,pi.trackedentityinstanceid as tei,
count(case when tedv.value = 'Working' then tedv.value end) Working,
count(case when tedv.value = 'Off day' then tedv.value end) Offday,
count(case when tedv.value = 'Leave' then tedv.value end) Leave
    from programstageinstance psi
    inner join programinstance pi on pi.programinstanceid = psi.programinstanceid
    inner join trackedentitydatavalue tedv on tedv.programstageinstanceid = psi.programstageinstanceid
    inner join dataelement de on de.dataelementid = tedv.dataelementid
    inner join trackedentityinstance tei on tei.trackedentityinstanceid = pi.trackedentityinstanceid
    where psi.executiondate between '2017-01-01' and '2019-06-01'
    and de.uid in ('x2222EGfY4K')
    and psi.programstageid in (select programstageid 
                                from programstage 
                                where uid = 'CLoZpO22228')
    and tei.organisationunitid in (select organisationunitid 
                                    from organisationunit 
                                    where path like '%Spd2222fvPr%')
    group by pi.trackedentityinstanceid,de.uid,tei.organisationunitid,tedv.value

我该如何实现?

1 个答案:

答案 0 :(得分:2)

我会尝试JSON方法。我做了一个分步的小提琴:

demo:db<>fiddle

SELECT 
    id, id2,
    elements ->> 'code' AS code,
    SUM((elements ->> 'value')::int) AS value
FROM (
    SELECT 
        id,
        id2,
        json_build_object('code', 'working', 'value', working) AS working, 
        json_build_object('code', 'leave', 'value', leave) AS leave, 
        json_build_object('code', 'off_day', 'value', off_day) AS off_day
    FROM
        mytable
) s,
unnest(ARRAY[working, leave, off_day]) as elements
GROUP BY 1,2,3
HAVING SUM((elements ->> 'value')::int) > 0
相关问题