标签:
问题描述:两张表A和B,各有一个字段,更新时间A.MODIFIED_TM和B.MODIFIED_TM,A表为主表,更新时间不为空,但是B表更新时间可能为空,现在要取A、B两表时间最新的那个,B.MODIFIED_TM若为空就取A.MODIFIED_TM,例如:
表A
ID MODIFIED_TM
1 2013/3/10 18:07:12
2 2013/4/10 18:07:12
3 2013/5/10 18:07:12
表B
ID MODIFIED_TM
1 2014/3/11 18:07:12
null null
3 null
结果
1 2014/3/11 18:07:12
2 2013/4/10 18:07:12
3 2013/5/10 18:07:12
左连接
方式一:
SELECT A.ID AS ID,
DECODE(B.MODIFIED_TM,
NULL,
A.MODIFIED_TM,
GREATEST(A.MODIFIED_TM, B.MODIFIED_TM)) AS MODIFIED_TM
FROM A
LEFT JOIN B
ON A.ID = B.ID;
方式二:
SELECT A.ID AS ID,
CASE
WHEN B.MODIFIED_TM IS NOT NULL THEN
GREATEST(A.MODIFIED_TM, B.MODIFIED_TM)
ELSE
A.MODIFIED_TM
END AS MODIFIED_TM
FROM A
LEFT JOIN B
ON A.ID = B.ID;
方式三:
SELECT A.ID,
GREATEST(NVL(B.MODIFIED_TM, DATE ‘1900-01-01‘),
NVL(A.MODIFIED_TM, DATE ‘1900-01-01‘))
FROM A, B
WHERE A.ID = B.ID(+)
ORDER BY A.ID;
两张表A和B,各有一个字段,更新时间A.MODIFIED_TM和B.MODIFIED_TM,A表为主表,更新时间不为空,但是B表更新时间可能为空,现在要取A、B两表时间最新的那个,B.MODIFIED
标签:
原文地址:http://blog.csdn.net/runycq/article/details/42406567