[英]SQL query in postgresql to produce pivot table report to turn columns into rows
Unsure how to create a pivot report query in postgres (newbie to postgres) based on the following tables/report layout.不确定如何根据以下表格/报告布局在 postgres(postgres 新手)中创建数据透视报告查询。
Please note that I am not able to change the structure of these tables as out of my control.请注意,由于我无法控制,我无法更改这些表的结构。
STOCK_REF ( sr_id, stock_name )
STOCK_INVENTORY ( si_id, sr_id, stock_count ) * where sr_id here is a foreign key constraint
Sample data for each table may include the following:每个表的样本数据可能包括以下内容:
STOCK_REF
1 GUITAR
2 BASS
3 DRUMS
4 KEYBOARDS
STOCK_INVENTORY
1 1 10
2 2 5
3 3 2
4 4 15
Using the above two tables, I need to produce a report that looks like:使用上面的两个表,我需要生成一个如下所示的报告:
STOCK NAME COUNT
--------------------------- --------
GUITAR 10
BASS 5
DRUMS 2
KEYBOARDS 15
which is like a pivot table.这就像一个数据透视表。
The thing is, I can write the query that will produce the stock name as columns with counts but I actually need to have the stock name and counts as rows, like above.问题是,我可以编写查询,将股票名称生成为带有计数的列,但实际上我需要将股票名称和计数作为行,如上。
Any help with this postgres query would be ideal任何有关此 postgres 查询的帮助都是理想的
Try the query below.试试下面的查询。 It's simple SQL.这是简单的SQL。 I think POSTGRES don't determine too much here...我认为 POSTGRES 在这里没有确定太多......
SELECT stock_name AS "STOCK NAME", stock_count AS "COUNT"
FROM STOCK_REF INNER JOIN STOCK_INVENTORY
ON (STOCK_REF.sr_id = STOCK_INVENTORY.sr_id)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.