gpt4 book ai didi

sql - crosstab() 查询移动列

转载 作者:行者123 更新时间:2023-11-29 13:36:55 25 4
gpt4 key购买 nike

我在 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)

问题是结果都左移了。
例如,如果一个位置的类(class)应该在 hour_8 显示,它会在 hour_0 显示。
这适用于所有地点的所有类(class)。它们都是左对齐的。

我哪里出错了?

最佳答案

由于没有样本数据,我只能猜测。以下是让我印象深刻的内容:
您的交叉表函数中没有 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 :

In practice the SQL query should always specify ORDER BY 1,2 to ensure that the input rows are properly ordered, that is, values with the same row_name are brought together and correctly ordered within the row.

关于sql - crosstab() 查询移动列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7722824/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com