根据某些条件,我们必须更改加入表

时间:2016-11-09 13:37:06

标签: db2

我面临一个问题。我正在创建一个像Temp_district一样的proc。

因为根据某些条件,我们必须更改连接表。

like if(year=2016) then 
select * from table1 a join table2 b  on (a.id=b.id) join table3 c on (c.id=b.id) join table4 d on d.id=a.id


if(year<>2016) then
select * from table1 a join table2 b  on (a.id=b.id) join table3 c on (c.id=b.id) join table5 e on d.id=a.id;

查询几乎相同,并且查询太多了,因为如果年份不是2016年,那么只有一个表会被更改,即table4到table5

有下面的内容吗

if(year=2016) then 
with temp_table_2016 (select * from table4)
else with temp_table_2016 (select * from table6)

这样在单个查询中我可以用temp_table_2016替换table4或table5,具体取决于它将从所需的表中获取数据。

2 个答案:

答案 0 :(得分:2)

所以只需加入两个相反的条件:

SELECT t.*,
        COALESCE(t4.col,t5.col) as col,
        COALESCE(t4.col2,t5.col2) as col2,
       ....
FROM t
LEFT JOIN t4 ON(t.id = t4.id AND year = 2016)
LEFT JOIN t5 ON(t.id = t5.id AND year <> 2016)

您需要在所有表格列上添加COALESCE(),因此只会显示相应的数据。如果您不在乎,可以同时选择它们,其中一个始终为NULL

答案 1 :(得分:0)

如果您使用MSSQL,可以使用如下所示:

DECLARE @secondtable NVARCHAR(20)

if(year=2016)
BEGIN
SET @secondtable = 'table4'
END

if(year<>2016)
BEGIN
SET @secondtable = 'table5'
END



EXEC('select * from table1 a join table2 b
 on (a.id=b.id) join table3 c on (c.id=b.id) join '+@secondtable+' d on d.id=a.id')
相关问题