我有多个具有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;
1条答案
按热度按时间z6psavjg1#
假设
id
列是每个表的键,您可以连接它们(可能使用完全外部连接),然后使用GREATEST()
获取最新日期。例如:
EDIT:如果您的DB2版本没有实现
GREATEST()
,您可以用[相当长的]CASE
子句替换它:或者,您也可以自己实现该函数,这非常简单。例如:
请参阅db<>fiddle 1中此自定义函数的运行示例。
编辑#2:处理空值
空值不是值,数据库的行为是正确的。如果存在未知日期,引擎将无法确定哪个日期更大,并返回
UNKNOWN
--以空值的形式。现在,如果你想让null的行为和C、Java、PHP等编程语言一样,那么你可以1)使用大量的
CASE
/COALESCE
子句,或者你可以简单地修改你的自定义函数,让它按照你喜欢的方式工作。然后,您可以看到它的运行情况:
结果:
请参阅db<>fiddle 2上的运行示例。