我从3个表(日期和数量)中检索数据,某些数据可能重叠但不确定哪些表。例如,某些日子可能重叠 表t1和t2但不在t3中, 或t2和t3但不在t1 或t1和t3但不在t2
如果我执行完全连接,我最终会得到很多空值和三个不同的日期列。
如何获取格式化数据:
date,qty1, qty2, gty3
其中[date]
将包含3个表的所有日期?
零将替换所有空值
07/02/2012 || 2 || 0 || 7
CREATE TABLE t1 (
[date] [nvarchar](10)
,qtyt1 [int]
)
CREATE TABLE t2 (
[date] [nvarchar](10)
,qtyt2 [int]
)
CREATE TABLE t3 (
[date] [nvarchar](10)
,qtyt3 [int]
)
insert into t1 values ('05/02/2012', 2)
insert into t1 values ('07/02/2012', 3)
insert into t2 values ('06/02/2012', 4)
insert into t2 values ('08/02/2012', 5)
insert into t3 values ('07/02/2012', 7)
insert into t3 values ('08/02/2012', 11)
select * from t1
full join t2 on t1.date = t2.date
full join t3 on t2.date = t3.date
答案 0 :(得分:5)
SELECT COALESCE(t1.date, t2.date, t3.date) AS date,
qtyt1,
qtyt2,
qtyt3
FROM t1
FULL JOIN t2
ON t1.date = t2.date
FULL JOIN t3
ON ISNULL(t2.date, t1.date) = t3.date