有没有人知道如何在PostgreSQL中创建交叉表查询?
例如,我有下表:
Section Status Count
A Active 1
A Inactive 2
B Active 4
B Inactive 5
Run Code Online (Sandbox Code Playgroud)
我想查询返回以下交叉表:
Section Active Inactive
A 1 2
B 4 5
Run Code Online (Sandbox Code Playgroud)
这可能吗?
有没有人过去常常使用tablefunc
多个变量,而不是只使用行名?文档说明:
对于具有相同row_name值的所有行,"额外"列应该是相同的.
我不知道如何在没有组合我想要转向的列的情况下如何做到这一点(我非常怀疑它会给我我需要的速度).一种可能的方法是将实体设为数字,并将其作为毫秒添加到localt,但这似乎是一种不稳定的方式.
我编辑了回答这个问题的数据:PostgreSQL Crosstab Query.
CREATE TEMP TABLE t4 (
timeof timestamp
,entity character
,status integer
,ct integer);
INSERT INTO t4 VALUES
('2012-01-01', 'a', 1, 1)
,('2012-01-01', 'a', 0, 2)
,('2012-01-02', 'b', 1, 3)
,('2012-01-02', 'c', 0, 4);
SELECT * FROM crosstab(
'SELECT timeof, entity, status, ct
FROM t4
ORDER BY 1,2,3'
,$$VALUES (1::text), (0::text)$$)
AS ct ("Section" timestamp, "Attribute" character, "1" int, "0" int);
Run Code Online (Sandbox Code Playgroud)
返回:
Section | Attribute | 1 …
我有一张“瘦高”事实表:
CREATE TABLE facts(
eff_date timestamp NOT NULL,
update_date timestamp NOT NULL,
symbol_id int4 NOT NULL,
data_type_id int4 NOT NULL,
source_id char(3) NOT NULL,
fact decimal
/* Keys */
CONSTRAINT fact_pk
PRIMARY KEY (source_id, symbol_id, data_type_id, eff_date),
)
Run Code Online (Sandbox Code Playgroud)
我想“透视”这个报告,所以标题看起来像这样:
eff_date, symbol_id, source_id, datatypeValue1, ... DatatypeValueN
Run Code Online (Sandbox Code Playgroud)
即,对于 eff_date、symbol_id 和 source_id 的每个唯一组合,我想要一行。
但是,postgresql crosstab() 函数只允许键列。
有任何想法吗?