我在下面查询我从连接表日志和设备获取数据但是来自表设备的b.id也在另一个名为equipment2且具有相同列名的表中。所以我必须编写一个查询,其中如果设备表在该id列上具有空值或空值,则必须将表设备2上的记录连接到表日志,否则它必须连接表设备和日志。
SELECT TO_CHAR (a.LOG_DATE, 'mm/dd/yyyy HH:MI:SS') LOG_DATE,
b.id,
a.atid,
a.l_type,
a.l_subtype,
a.eq,
a.name,
a.comments
FROM log a, (equipment b or equipment2 b)
WHERE a.eqid = b.eqid(+)
AND log_date BETWEEN TO_DATE ('07/01/2013', 'MM/DD/YYYY')
AND TO_DATE ('07/08/2070', 'MM/DD/YYYY')
GROUP BY a.log_date,
b.id,
a.atid,
a.l_type,
a.l_subtype,
a.eq,
a.name,
a.comments
ORDER BY b.id;
答案 0 :(得分:1)
假设子记录总是在设备或设备2中,但从不两者兼而有之,您只需添加带有外连接的设备2,并使用NVL()来选择非空值:
SELECT TO_CHAR (a.LOG_DATE, 'mm/dd/yyyy HH:MI:SS') LOG_DATE,
nvl(b.id,b2.id),
a.atid,
a.l_type,
a.l_subtype,
a.eq,
a.name,
a.comments
FROM
log a,
equipment b,
equipment2 b2
WHERE
a.eqid = b.eqid(+)
AND a.eqid = b2.eqid(+)
AND log_date BETWEEN TO_DATE ('07/01/2013', 'MM/DD/YYYY')
AND TO_DATE ('07/08/2070', 'MM/DD/YYYY')
ORDER BY 2
这也假设您只选择了一个不会填充NULL的列。例如,如果设备/设备2还包含可能为空的“名称”列,则需要一些额外的逻辑:
case when b.id is null then b2.name else b.name end
答案 1 :(得分:0)
另一种可能性是合并两个设备表并加入它。假设表格结构在设备和设备上是相同的2,否则您将需要选择特定的字段。否则...
SELECT *
INTO #equipTemp
FROM equipment WHERE ID IS NOT NULL
UNION ALL
SELECT * FROM equipment2 WHERE ID IS NOT NULL
SELECT TO_CHAR (a.LOG_DATE, 'mm/dd/yyyy HH:MI:SS') LOG_DATE,
b.id,
a.atid,
a.l_type,
a.l_subtype,
a.eq,
a.name,
a.comments
FROM log a, #eqipTemp b
WHERE a.eqid = b.eqid(+)
AND log_date BETWEEN TO_DATE ('07/01/2013', 'MM/DD/YYYY')
AND TO_DATE ('07/08/2070', 'MM/DD/YYYY')
GROPU BY...