[英]PostgreSQL Query Using Crosstab
Now, I am leaning postgreSQL. 现在,我倾向于使用postgreSQL。 In the study, I found crosstab in postgreSQL. 在研究中,我在postgreSQL中找到了交叉表。 I tried to apply this function to my customized table, but it dose not work. 我试图将此功能应用于我的自定义表格,但无法正常工作。 please help!! 请帮忙!!
This is my Table 这是我的桌子
year | type | count
------+----------+----
2015 | AS | 6
2015 | HY | 6
2015 | KR | 6
2015 | SE | 6
2016 | AS | 2
2016 | HY | 2
2016 | KR | 2
2016 | SE | 2
2017 | AS | 1
2017 | HY | 1
2017 | KR | 1
2017 | SE | 1
2018 | AS | 2
2018 | HY | 2
2018 | KR | 2
2018 | SE | 2
I want to change this table like this 我想这样改变这张桌子
year | AS | HY | KR | SE |
----------------------------------
2015 | 6 | 6 | 6 | 6 |
2016 | 2 | 2 | 2 | 2 |
2017 | 1 | 1 | 1 | 1 |
2018 | 2 | 2 | 2 | 2 |
To make that table, I designed query using crosstab, but dose not work! 为了制作该表,我使用交叉表设计了查询,但是无法正常工作!
Please Let me know the query of this problem. 请让我知道这个问题的查询。
You could achieve this without Crosstab
, you can use Aggregate
function. 您可以在没有Crosstab
情况下实现此目的,可以使用Aggregate
函数。
Query : 查询:
select
year,
max(counts) filter (where type = 'AS') as "AS",
max(counts) filter (where type = 'HY') as "HY",
max(counts) filter (where type = 'KR') as "KR",
max(counts) filter (where type = 'SE') as "SE"
from
tbl
group by
year
order by
year asc
Demo <> DB Fiddle 演示<> DB Fiddle
And if you are try learning Crosstab
this answer are really great and explain really well about to do pivot use Crosstab
. 而且,如果您尝试学习Crosstab
此答案非常有用,并且很好地解释了如何使用Crosstab
进行透视。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.