postgresql - Postgres : buckets always filled from left in crosstab query

标签 postgresql crosstab

我的查询是这样的:

SELECT mthreport.*
FROM crosstab
('SELECT 
to_char(ipstimestamp, ''mon DD HH24h'') As row_name, 
varid::text || log.varid || ''_'' || ips.objectname::text As bucket, 
COUNT(*)::integer As bucketvalue
FROM loggingdb_ips_boolean As log 
INNER JOIN IpsObjects As ips 
ON log.Varid=ips.ObjectId
WHERE ((log.varid = 37551) 
OR (log.varid = 27087) 
OR (log.varid = 50876)
OR (log.varid = 45096)
OR (log.varid = 54708)
OR (log.varid = 47475)
OR (log.varid = 54606)
OR (log.varid = 25528)
OR (log.varid = 54729))
GROUP BY to_char(ipstimestamp, ''yyyy MM DD HH24h''), row_name, objectid, bucket        
ORDER BY to_char(ipstimestamp, ''yyyy MM DD HH24h''), row_name, objectid, bucket' )

As mthreport(item_name text,  varid_37551 integer, 
            varid_27087  integer , 
            varid_50876  integer , 
            varid_45096  integer , 
            varid_54708  integer , 
            varid_47475  integer , 
            varid_54606  integer , 
            varid_25528  integer , 
            varid_54729  integer , 
            varid_29469 integer)

可以使用此连接字符串针对测试表测试查询: "host=bellariastrasse.com port=5432 dbname=IpsLogging user=guest password=guest"

查询语法正确,运行良好。我的问题是 COUNT(*) 值总是填充最左边的列。然而,在许多情况下,左边的列应该有一个零,或者一个 NULL,并且只有第 2(或第 n)列应该被填充。我的大脑在融化,我不知道出了什么问题!

最佳答案

您的问题的解决方案是使用带有两个参数crosstab() 变体。

第二个参数(另一个查询字符串)生成输出列的列表,以便正确分配数据查询(第一个参数)中的 NULL 值。

检查 manual for the tablefunc extension ,特别是 crosstab(text, text) :

The main limitation of the single-parameter form of crosstab is that it treats all values in a group alike, inserting each value into the first available column. If you want the value columns to correspond to specific categories of data, and some groups might not have data for some of the categories, that doesn't work well. The two-parameter form of crosstab handles this case by providing an explicit list of the categories corresponding to the output columns.

强调我的。我最近发布了几个相关的答案hereherehere .

关于postgresql - Postgres : buckets always filled from left in crosstab query,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11074489/

相关文章:

postgresql - Postgres colpivot 函数不返回任何内容

sql - 使用交叉表将行转换为列失败

postgresql - 执行动态交叉表查询

sql - Postgresql根据其JSONB字段值总和更新记录列

sql - has_table 键的日期期间

postgresql - Postgres : get all columns from all views in schema

sql - 具有动态列数的 PostgreSQL 查询

sql - 如何为从多边形顶点生成的点创建 PostgreSQL 分区序列?

mysql - 如何在 MySQL 8 中通过 int 而不是通过名称从嵌套 JSON 中获取

sql - 将我的列转换为 postgresql 中的行而不创建任何扩展