Christian Fagerland
Christian Fagerland

Reputation: 33

Joining data when one table has null value

I have two tables, and I join them together on the date column. This works great besides when one table are missing the date.

I.e, in table two, I don't have 10.10.2016. I would still love that line to appear in the result, since this is a day I want to show that there has been no activity.

This is for a bar: I have one table where they register the count on the beer tap, and one who keeps track of sold ones.

If they are closed one day, they don't actually sell anything, but they still want the staff to register the number of tapped beers, just in case.

The data from 10.10.2016 would be something like this then:

Table 1 (sales, not open 10.10 = no data stored at all)

Date Sold 10.08 22 10.09 31 10.11 54

Table 2 (Tapped, they count every day = have data 10.10)

Date Tapped 10.08 23 10.09 31 10.10 0 10.11 54

I want the result to show it like this:

Date Tapped Sold Diff 10.08 23 22 1 10.09 31 31 0 10.10 0 0 0 10.11 54 54 0

But I cannot get this to work, because when I join in table two, it can't connect the "sold" and "tapped" ones from 10.10 since I don't have a way to mach them.

Is there any way of doing this?

Upvotes: 1

Views: 85

Answers (3)

dedso3
dedso3

Reputation: 36

simple statement

SELECT tapped.date as date, IFNULL(tapped.tapped,0) as tapped, IFNULL(sales.sold,0) as sold, IFNULL(tapped.tapped - sales.sold,0) as diff
FROM
tapped
LEFT OUTER JOIN sales ON sales.date = tapped.date
ORDER BY
tapped.date ASC

Upvotes: 0

Unnikrishnan R
Unnikrishnan R

Reputation: 5031

Use a left or right join.

Below sample shows how to use RIGHT JOIN.

SELECT t2.Date,t2.Tapped,ISNULL(t1.sold,0) sold,t2.Tapped-ISNULL(t1.sold,0) as Diff
FROM Table1 t1 
 RIGHT JOIN Table2  t2 
   ON t1.Date=t2.Date

Upvotes: 0

Chanukya
Chanukya

Reputation: 5873

CREATE TABLE #A
(
DATE NUMERIC
(22,6),SOLD INT
)
INSERT INTO #A VALUES
(10.08,22), 
(10.09,31),
(10.11,54)

CREATE TABLE #B
(
DATE NUMERIC
(22,6),TAPPED INT
)

INSERT INTO #B VALUES              
(10.08,23),
(10.09,31),
(10.10,0),
(10.11,54)

SELECT A.DATE,A.TAPPED,ISNULL(B.SOLD,0)SOLD,A.TAPPED-ISNULL(B.SOLD,0) AS DIFFRENCE 
 FROM #B  A LEFT JOIN #A B ON  A.DATE=B.DATE

Upvotes: 1

Related Questions