[英]How to create table where columns in first table are fields in another table?
TABLE_1 表格1
t1_id name
-------------
1 mark
2 stieve
TABLE_2 表_2
t2_id month amt t1_id
----------------------------
1 jan 200 1
2 feb 400 1
3 jan 500 2
Expected output 预期产量
VIEW_TABLE_3 VIEW_TABLE_3
T1_ID name jan feb
-----------------------
1 mark 200 400
2 stieve 500 0
In the VIEW_TABLE_3 we need to make columns Jan and Feb which are fields in the Table_2 , with their respective amt. 在VIEW_TABLE_3中,我们需要创建Jan和Feb列,它们是Table_2中的字段,并带有各自的amt。
Please help how can get this output? 请帮助如何获得此输出?
I don't know which one RDBMS you are using, but In SQL-Server you can use PIVOT
in following: 我不知道您使用的是哪个RDBMS,但是在SQL Server中,您可以在以下方式使用
PIVOT
:
CREATE TABLE #t1
(
t1_id INT,
name NVARCHAR(60)
)
CREATE TABLE #t2
(
t2_id INT,
[month] NVARCHAR(20),
amt INT,
t1_id INT
)
INSERT INTO #t1 VALUES (1, 'Mark'), (2, 'Stieve')
INSERT INTO #t2 VALUES
(1, 'jan', 200, 1),
(2, 'feb', 400, 1),
(3, 'jan', 500, 2)
SELECT t1_id, Name, COALESCE(jan, 0) jan, COALESCE(feb, 0) feb
FROM (
SELECT #t1.t1_id, #t1.Name, #t2.[month], #t2.amt
FROM #t1
JOIN #t2 ON #t1.t1_id = #t2.t1_id
)x
PIVOT
(
MAX([amt])
FOR [month] IN ([jan], [feb])
)piv
DROP TABLE #t1
DROP TABLE #t2
OUTPUT: 输出:
t1_id Name jan feb
1 Mark 200 400
2 Stieve 500 0
In PostgreSQL you can install the tablefunc
extension: 在PostgreSQL中,您可以安装
tablefunc
扩展名:
CREATE EXTENSION tablefunc;
In that extension you will find the crosstab(text, text)
function . 在该扩展中,您将找到
crosstab(text, text)
函数 。 This is an ugly function to work with (putting it mildly), but it will do what you want: 这是一个很难使用的功能(轻巧地使用它),但是它将执行您想要的操作:
SELECT * FROM crosstab(
'SELECT t1_id, name, month, coalesce(amount, 0) FROM table_1 JOIN table_2 USING (t1_id)',
'VALUES (''jan''), (''feb''), (''mar''), (''apr''), (''may''), (''jun''), (''jul''), (''aug''), (''sep''), (''oct''), (''nov''), (''dec'')'
) AS (
id int, name varchar,
jan int, feb int, mar int, apr int, may int, jun int,
jul int, aug int, sep int, oct int, nov int, dec int
);
The first parameter specifies the data to be cross-tabulated, in a specific format (check the documentation), the second parameter specifies the categories. 第一个参数指定要交叉列出的数据,格式为特定格式(请参阅文档),第二个参数指定类别。 I am assuming here that the months could be any of the year.
我在这里假设月份可以是一年中的任何一年。
If you can have multiple records for the same person in a single month, then you can sum coalesce(amount, 0)
in the first parameter, and add a GROUP BY 1, 2, 3
clause. 如果您可以在一个月内拥有同一个人的多个记录,则可以在第一个参数中求和
coalesce(amount, 0)
总和,并添加GROUP BY 1, 2, 3
子句。
Finally, you can wrap this in a view: 最后,您可以将其包装在视图中:
CREATE VIEW view_table_3 AS
SELECT * FROM crosstab(...
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.