我正在尝试使用PostgreSQL 9.5交叉表查询创建周转时间报告,其中引荐被分配到第1,2,3,4,... 4(见下面的输出)。 我已经让查询工作了,但是如果我运行查询并且缺少第2天的值,则整行会向左移动一个单元格。所以第二天持有第3天的价值,第3天持有第4天的价值等等...... 有人可以帮助我如何保持这个例子中的第2天是空白还是零而不是将行向左移动?
提前致谢。
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 )
输出:
indicator Day1 Day2 Day3 Day4 Day > 4
--------------------------------------
INDICATOR1 60 15 13 10 5
答案 0 :(得分:6)
使用函数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)