【发布时间】:2022-01-06 06:30:19
【问题描述】:
我有多个具有 date_modified 列的表,我需要使用所有这些表创建一个视图,但 date_modified 应该是这些表中 date_modified 的最大值。
table1
id vendor_number fiscal_year date_created date_modified
1 124 2021 2021/11/01 2021/11/02
2 231 2021 2021/11/01 2021/11/03
3 232 2021 2021/11/02 NULL
4 234 2021 2021/11/02 NULL
table2
id fiscal_year discount_amt date_created date_modified
1 2021 10.30 2021/11/01 2021/11/03
2 2021 15.23 2021/11/01 2021/11/02
3 2021 17.45 2021/11/02 2021/11/02
4 2021 18.49 2021/11/02 NULL
table3
id vendor_number date_created date_modified
1 124 2021/11/01 2021/11/04
2 231 2021/11/01 2021/11/01
3 232 2021/11/01 2021/11/03
4 234 2021/11/02 2021/11/03
Required Output :
id|fiscal_year|discount_amt|vendor_number|date_created|date_modified
1 | 2021 | 10.30 | 124 | 2021/11/01 | 2021/11/04
2 | 2021 | 15.23 | 231 | 2021/11/01 | 2021/11/03
3 | 2021 | 17.45 | 232 | 2021/11/02 | 2021/11/03
4 | 2021 | 18.49 | 234 | 2021/11/02 | 2021/11/03
查看 SQL:
CREATE VIEW view_data
AS
SELECT T1.id, T1.fiscal_year, T2.discount_amt, T3.vendor_number, T1.date_created, max(multiple date_modified columns..from multiple tables..)
FROM table1 AS T1
LEFT JOIN table2 AS T2
ON T1.id = T2.id
LEFT JOIN T3 v
ON T1.vendor_number = T3.vendor_number;
【问题讨论】:
-
date_created的规则是什么?一个简单的select id, max (date_modified) as date_modified from (select id, date_modified from table1 union all select id, date_modified from table2 union all select id, date_modified from table3) group by id声明有什么问题? -
我需要从多个表中创建一个具有最大 date_modified 的视图。我添加了一个示例视图定义并更新了表结构。
date_created将从主表`table1`中使用。这需要在 DB2 中完成。 -
您使用
fiscal_year列连接tabl1和table2,但显示此连接的2 个输出行,而它必须是4 行,因为两个表都有2 行,每行具有相同的@ 987654329@。你能解释一下,为什么table1的第一行连接到table2的第一行(而不是第二行)?你没有弄乱连接列吗? -
是的,可能是我给出的示例不是我实际拥有的.. 我只是想实现 date_modified 列应该是所有表的所有 date_modified 列的最大值。请忽略连接或表数据,输出只是为了显示所需的结果。