Netezza aggregation issue (pivot)

2019-07-21 08:43发布

问题:

I'm using Netezza to generate a report and I have the following query

select  b.group_name,a.group_id, PASS_FAIL, COUNT(*) from log a
join group b on a.group_id=b.group_id
group by b.group_name,a.group_id, PASS_FAIL

It collects information on the number of passes and failures in a table like this:

    GROUP_NAME  GROUP_ID    PASS_FAIL   COUNT
    GROUP1        4            FAIL     382
    GROUP1        4            PASS     339

How can I change the query so that I can use PASS and FAIL as the columns.

GROUP_NAME  GROUP_ID      PASS      FAIL
GROUP1        4           339       382

Pivot isn't available in Netezza so I was wondering what the best way to go about this would be. What is the best way to do this?

回答1:

I don't have direct experience with netezza but from what I've read it supports the standard SQL solution of SUM/CASE

SELECT 
    GROUP_NAME,
    GROUP_ID,
    SUM(CASE WHEN PASS_FAIL = 'PASS' THEN 1 ELSE 0 END) as PASS,
    SUM(CASE WHEN PASS_FAIL = 'FAIL' THEN 1 ELSE 0 END) as FAIL
FROM 
    log a
    join group b 
    on a.group_id=b.group_id
GROUP BY 
    b.group_name,
    a.group_id


回答2:

Just do a self-join of modified versions of your query above, each of which produces one of the pass and fail columns that you need (note that I haven't tested this since I don't have an installation of Netezza to work with):

select group_name,group_id,pass,fail
from(
    select group_name,group_id,pass
    from(
        select  b.group_name,a.group_id, COUNT(*) as pass
        from log a
        join group b on a.group_id=b.group_id
        where pass_fail='PASS'
        group by b.group_name,a.group_id
        )x
    )p
join(
    select group_name,group_id,fail
    from(
        select  b.group_name,a.group_id, COUNT(*) as fail
        from log a
        join group b on a.group_id=b.group_id
        where pass_fail='FAIL'
        group by b.group_name,a.group_id
        )y
    )f
on(p.group_name=f.group_name and p.group_id=f.group_id);


标签: sql netezza