I retrieve data form 3 tables (date and qty), some data may overlap but is not sure which tables. For example some days may overlap in tables t1 and t2 but not in t3, or t2 and t3 but not in t1 or t1 and t3 but not in t2
If I perform a full join I end up with lots of nulls and three different date columns.
How can I get data to format:
date,qty1, qty2, gty3
where [date]
would contain all days form 3 tables?
Zero would replace all null values
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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With