我在postgres中使用交叉表功能。基本SQL是:
select distinct
o_location,
co_name,
o_date,
o_ndate,
o_day,
o_hour,
o_type
from outputs_txt
left join courses on o_course = co_foreign
left join locations on o_location = l_code
where o_date = '2011-10-10'
order by o_hour
我的交叉表查询是
SELECT *
FROM crosstab(
'SELECT DISTINCT
COALESCE(o_location, '''')
,o_hour AS hour
,c.co_name
FROM outputs_txt AS d
LEFT JOIN courses AS c
on o_course = c.co_foreign
LEFT JOIN locations as a
on o_location = a.l_code
WHERE d.o_date = ''2011-10-10'''
)
AS ct(
o_location varchar
,hour_0 varchar
,hour_1 varchar
,hour_2 varchar
,hour_3 varchar
,hour_4 varchar
,hour_5 varchar
,hour_6 varchar
,hour_7 varchar
,hour_8 varchar
,hour_9 varchar
,hour_10 varchar
,hour_11 varchar
,hour_12 varchar
,hour_13 varchar
,hour_14 varchar
,hour_15 varchar
,hour_16 varchar
,hour_17 varchar)
问题是结果都向左移动了
例如,如果某个地点的课程应显示在hour_8
上,则会显示在hour_0
中
这适用于所有地点的所有课程。它们都是左对齐的。
我哪里错了?
答案 0 :(得分:1)
由于没有样本数据,我只能猜测。这是让我感到震惊的事:
交叉表功能中没有 ORDER BY
。我加了一个:
SELECT *
FROM crosstab(
'SELECT DISTINCT
COALESCE(o_location, '''')
,o_hour AS hour
,c.co_name
FROM outputs_txt AS d
LEFT JOIN courses AS c ON o_course = c.co_foreign
LEFT JOIN locations as a ON o_location = a.l_code
WHERE d.o_date = ''2011-10-10''
ORDER BY 1,2'
)
AS ct(
o_location varchar
,hour_0 varchar
,hour_1 varchar
,hour_2 varchar
,hour_3 varchar
,hour_4 varchar
,hour_5 varchar
,hour_6 varchar
,hour_7 varchar
,hour_8 varchar
,hour_9 varchar
,hour_10 varchar
,hour_11 varchar
,hour_12 varchar
,hour_13 varchar
,hour_14 varchar
,hour_15 varchar
,hour_16 varchar
,hour_17 varchar)
如果您首先需要hour_0
,则必须按o_hour
订购。我引用manual on crosstab functions:
实际上,SQL查询应始终指定ORDER BY 1,2来确保 输入行是否正确排序,即带有的值 将相同的row_name放在一起并在其中正确排序 行。