gpt4 book ai didi

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

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

我的查询是这样的:

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/

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