sql - PostgreSQL 交叉表函数

标签 sql postgresql pivot crosstab

我对交叉表功能有一些问题。

我的表“t”是

date;name;hour;cause;c_p
"2013-06-12";167;14;0;2
"2013-06-12";167;16;0;3
"2013-06-12";167;16;0;4
"2013-06-12";167;19;1;1
"2013-06-12";167;19;0;4

我会有这个“数据透视表”t_pivot

day;name;hour;cause_0;cause_1
"2013-06-12";167;14;2;0 -----sum(c_p)
"2013-06-12";167;16;7;0
"2013-06-12";167;19;4;1

SQL代码为

SELECT  * from crosstab (
    'SELECT  day,name,hour,cause, SUM(c_p) AS c_p
        FROM t
        GROUP BY 1,2,3,4
        ORDER BY 3 ',

     'SELECT DISTINCT cause 
         FROM i
         ORDER BY 1')

AS t_pivot (day date, name integer,hour integer, cause_0 integer,cause_1 integer)

查询结果是一个由“ORDER BY”决定的行表

ORDER BY 3
"2013-06-12";167;14;4;1

ORDER BY 1, ORDER BY 2
"2013-06-12";167;14;7;1

错在哪里? 谢谢 f.

最佳答案

我没有使用过 crosstab 函数,现在无法对其进行测试(sqlfiddle 上没有 tablefunc 扩展),但一般来说,如果我需要这样的数据透视表,我更喜欢简单的 SQL:

select
    date,
    hour,
    sum(case when cause = 0 then c_p else 0 end) cause_0,
    sum(case when cause = 1 then c_p else 0 end) cause_1
from t
group by date, hour
order by hour

sql fiddle demo

我认为以后更容易维护和阅读(但这是主观意见)。

更新 这个有效(小时用作 row_name,日期和名称是 extra 列):

SELECT  * from crosstab (
    'select hour, date, name, cause, sum(c_p) as c_p
     from t
     group by 1, 2, 3, 4
     order by 1',
    'select distinct cause from t order by 1')
AS t_pivot (hour integer, date timestamp, name integer, cause_0 integer,cause_1 integer)

来自 documentation :

source_sql is a SQL statement that produces the source set of data. This statement must return one row_name column, one category column, and one value column. It may also have one or more "extra" columns. The row_name column must be first. The category and value columns must be the last two columns, in that order. Any columns between row_name and category are treated as "extra". The "extra" columns are expected to be the same for all rows with the same row_name value.

还有

In practice the source_sql query should always specify ORDER BY 1 to ensure that values with the same row_name are brought together. However, ordering of the categories within a group is not important. Also, it is essential to be sure that the order of the category_sql query's output matches the specified output column order.

关于sql - PostgreSQL 交叉表函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18765260/

相关文章:

java - 数据迁移时出现空值问题?

c# - 是否可以在 linq to Entity Framework 中选择一个字符串?

python - Pandas 数据透视多索引表,无聚合

sql - TSQL 透视多个列

postgresql - CentOS : Postgres 11 yum repo missing repomd. xml(Errno 14 404 未找到)

mysql - DATEDIFF 显示过去 30、60 和 90 天的购买情况

sql - 如何在不使用 xp_cmdshell 的情况下将 BLOB varbinary(max) 列导出到 CSV 或 excel?

mysql - 如何加快MySQL数据库中SQL查询的执行时间?

macos - 安装后无法连接到 Mac OS X 上的 Postgresql

sql - 选择列中具有特定值的行