Postgres 中多个字段的交叉表
Windows 上的 Postgres 13。假设我有一个这样的表:
Job_type Department User_id Op_code Times_executed
-------------------------------------------------------------------------------------
ACCOUNTING MANAGER Accounting Alice VA01 578
ACCOUNTING MANAGER Accounting Alice FBL1N 2256
ACCOUNTING MANAGER Accounting Alice FBL3N 16272
ACCOUNTING MANAGER Accounting Alice ME23N 1682
ACCOUNT ASSISTANT General Bob ME2L 876
ACCOUNT ASSISTANT General Bob VA04 25700
ACCOUNT ASSISTANT General Bob VF77 12393
ACCOUNT ASSISTANT General Bob MEXX 5182
我想使用 Postgres 中的 crosstab 函数来获得这样的数据透视表:
Job_type Department User_id Op1 times1 Op2 times2 Op3 times3 Op4 times4
ACCOUNTING MANAGER Accounting Alice VA01 578 FBL1N 2256 FBL3N 16272 ME23N 1682
ACCOUNT ASSISTANT General Bob ME2L 876 VA04 25700 VF77 12393 MEXX 5182
我尝试用我的交叉表基础知识,但我只设法获取操作代码,但不能获取时间:
SELECT * FROM crosstab(
'select user_id, job_type, tcode
from mytable
order by 1,2')
AS ct(row_name text, category_1 text, category_2 text, category_3 text, category_4 text);
可以按照上面的格式全部获取吗?
预先非常感谢。
Postgres 13 on Windows. Let's assume I have a table like this:
Job_type Department User_id Op_code Times_executed
-------------------------------------------------------------------------------------
ACCOUNTING MANAGER Accounting Alice VA01 578
ACCOUNTING MANAGER Accounting Alice FBL1N 2256
ACCOUNTING MANAGER Accounting Alice FBL3N 16272
ACCOUNTING MANAGER Accounting Alice ME23N 1682
ACCOUNT ASSISTANT General Bob ME2L 876
ACCOUNT ASSISTANT General Bob VA04 25700
ACCOUNT ASSISTANT General Bob VF77 12393
ACCOUNT ASSISTANT General Bob MEXX 5182
I'd like to use the crosstab function in Postgres to get a pivot table like this:
Job_type Department User_id Op1 times1 Op2 times2 Op3 times3 Op4 times4
ACCOUNTING MANAGER Accounting Alice VA01 578 FBL1N 2256 FBL3N 16272 ME23N 1682
ACCOUNT ASSISTANT General Bob ME2L 876 VA04 25700 VF77 12393 MEXX 5182
I tried with my basic knowledge of crosstab but I only managed to get the operation codes, but not the times:
SELECT * FROM crosstab(
'select user_id, job_type, tcode
from mytable
order by 1,2')
AS ct(row_name text, category_1 text, category_2 text, category_3 text, category_4 text);
Is it possible to get it all in the format above?
Thanks a lot in advance.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这是
crosstab()
函数的替代解决方案:您创建一个与要显示的列列表相对应的复合类型:
以下查询将提供预期结果:
请参阅 < a href="https://dbfiddle.uk/?rdbms=postgres_14&fiddle=b889de5b07bd2e04d8b78332a644fdd8" rel="nofollow noreferrer">dbfiddle。
here is an alternative solution to the
crosstab()
function :You create a composite type which corresponds to the list of columns to be displayed :
The following query will provide the expected result :
see the test result in dbfiddle.