简体   繁体   English

当一张表有空值时连接数据

[英]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.除了当一张桌子缺少日期时,这很有效。

Ie, in table two, I don't have 10.10.2016.即,在表二中,我没有 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: 2016 年 10 月 10 日的数据将是这样的:

Table 1 (sales, not open 10.10 = no data stored at all)表 1(销售,未开放 10.10 = 根本没有存储数据)

Date Sold 10.08 22 10.09 31 10.11 54

Table 2 (Tapped, they count every day = have data 10.10)表 2(点击,他们每天计数 = 有数据 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.但是我无法让它工作,因为当我加入表二时,它无法连接 10.10 中的“已售出”和“已挖掘”,因为我没有办法处理它们。

Is there any way of doing this?有没有办法做到这一点?

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

Use a left or right join .使用leftright join

Below sample shows how to use RIGHT JOIN .下面的示例显示了如何使用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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM