[英]sql query to get max date from multiple columns of multiple table in db2
I have multiple tables having date_modified column, and I need to create a view using all these tables but date_modified should be max of date_modified of these tables.我有多个具有 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
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
table3
id vendor_number date_created date_modified
1 124 2021/11/01 2021/11/04
2 231 2021/11/01 2021/11/01
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
VIEW SQL:查看 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.fiscal_year = T2.fiscal_year
LEFT JOIN T3 v
ON T1.vendor_number = T3.vendor_number;
Assuming the id
columns are keys of each table you can join them (using full outer join maybe) and then use GREATEST()
to get the latest date.假设
id
列是每个表的键,您可以加入它们(可能使用完全外部连接),然后使用GREATEST()
获取最新日期。
For example:例如:
create view v as
select
coalesce(a.id, b.id, c.id) as id,
b.fiscal_year,
b.discount_amt,
a.date_created,
greatest(a.date_modified, b.date_modified, c.date_modified) as date_modified
from table1 a
full join table2 b on b.id = a.id
full join table3 c on c.id = b.id or c.id = a.id
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.