Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to do PostgreSQL crosstab query there values are missing in the column

I'm trying to create a turn around time report using PostgreSQL 9.5 crosstab query where referrals are bucketed into days 1, 2, 3, 4, > 4 (see output below). I've got the query to work however, if I ran the query and day 2 values were missing the entire row shifts one cell left. So day two holds day 3's value, day 3 holds day 4's value, etc... Can someone help me on how I can keep day 2 in this example be blank or zero but not shift the row left?

Thanks in advance.

SCRIPT:

DROP TABLE IF EXISTS dt_temp;
CREATE TABLE dt_temp(id SERIAL, day int , referrals bigint);

INSERT INTO dt_temp(day, referrals) VALUES(1, 60);
INSERT INTO dt_temp(day, referrals) VALUES(2, 15);
INSERT INTO dt_temp(day, referrals) VALUES (3, 13);
INSERT INTO dt_temp(day, referrals) VALUES (4, 10);
INSERT INTO dt_temp(day, referrals) VALUES (5, 1);
INSERT INTO dt_temp(day, referrals) VALUES (6, 2);
INSERT INTO dt_temp(day, referrals) VALUES (7, 1);
INSERT INTO dt_temp(day, referrals) VALUES (8, 1);

Select * from crosstab(
    $$
    Select 'INDICATOR1' "INDICATOR", days::text, sum(referrals)::text     
from (
      SELECT CASE  
      WHEN day > 4 THEN '>4'
      ELSE day::text
      END "days",
   referrals
   FROM dt_temp
   ) "t"
group by 1,2
order by 2
$$
) AS dx2ref(Indicator text, Day1 text,  Day2 text, Day3 text, Day4 text, "Day > 4" text )

OUTPUT:

indicator  Day1 Day2 Day3 Day4 Day > 4
--------------------------------------
INDICATOR1 60   15   13   10   5
like image 502
codeBarer Avatar asked May 24 '16 21:05

codeBarer


1 Answers

Use the second form of the function crosstab(text source_sql, text category_sql):

select * from crosstab(
    $$
        select 'INDICATOR1' "INDICATOR", days::text, sum(referrals)::text     
        from (
            select case  
                when day > 4 then '>4'
                else day::text
            end "days",
            referrals
            from dt_temp
            ) "t"
        group by 1,2
        order by 2
    $$,
    $$
        select days from (values ('1'), ('2'), ('3'), ('4'), ('>4')) t(days)
    $$
) AS dx2ref(Indicator text, Day1 text,  Day2 text, Day3 text, Day4 text, "Day > 4" text )


 indicator  | day1 | day2 | day3 | day4 | Day > 4 
------------+------+------+------+------+---------
 INDICATOR1 | 60   | 15   | 13   | 10   | 5
(1 row) 
like image 185
klin Avatar answered Sep 28 '22 10:09

klin