我想加入两张桌子。
表A有一列,名为“Week”,包含52行:1,2,3,4,5,6等。 表2有三列,名为“Name”,“Week”和“Total”,包含10行:
'Bob', 1, 1
'Bob', 3, 1
'Joe', 4, 1
'Bob', 6, 1
我想将这些加在一起,以便我的数据如下:
NAME|WEEK|TOTAL
'Bob', 1, 1
'Bob', 2, 0
'Bob', 3, 1
'Bob', 4, 0
'Bob', 5, 0
'Bob', 6, 1
如您所见,一个简单的外连接。但是,当我尝试这样做时,无论我使用什么样的连接,我都没有得到预期的结果。
我的查询如下:
SELECT a.WEEK, b.Total
FROM Weeks a LEFT JOIN Totals b ON (a.Week = b.Week and b.Name ='Bob')
此查询的结果是
NAME|WEEK|TOTAL
'Bob', 1, 1
'Bob', 3, 1
'Bob', 6, 1
提前感谢您的帮助!
答案 0 :(得分:3)
我知道它的访问权限,但您的加入不正确。这里我们进入sql server..same概念,看看连接条件:
--dont worry about this code im just creating some temp tables
--table to store one column (mainly week number 1,2..52)
CREATE TABLE #Weeks
(
weeknumber int
)
--insert some test data
--week numbers...I'll insert some for you
INSERT INTO #Weeks(weeknumber) VALUES(1)
INSERT INTO #Weeks(weeknumber) VALUES(2)
INSERT INTO #Weeks(weeknumber) VALUES(3)
INSERT INTO #Weeks(weeknumber) VALUES(4)
INSERT INTO #Weeks(weeknumber) VALUES(5)
INSERT INTO #Weeks(weeknumber) VALUES(6)
--create another table with two columns storing the week # and a total for that week
CREATE TABLE #Table2
(
weeknumber int,
total int
)
--insert some data
INSERT INTO #Table2(weeknumber, total) VALUES(1, 100)
--notice i skipped week 2 on purpose to show you the results
INSERT INTO #Table2(weeknumber, total) VALUES(3, 100)
--here's the magic
SELECT t1.weeknumber as weeknumber, ISNULL(t2.total,0) as total FROM
#Weeks t1 LEFT JOIN #Table2 t2 ON t1.weeknumber=t2.weeknumber
--get rid of the temp tables
DROP TABLE #table2
DROP TABLE #Weeks
结果:
1 100
2 0
3 100
4 0
5 0
6 0
拿你的周数表(有一列的表:
SELECT t1.weeknumber as weeknumber
添加一个空检查以将空值替换为0.我认为访问中有一些内容,如ISNULL
:
ISNULL(t2.total, 0) as total
从第一张桌子开始你的加入,然后离开加入你在daynumber字段的第二张桌子。结果很简单:
SELECT t1.weeknumber as weeknumber, ISNULL(t2.total,0) as total FROM
#Weeks t1 LEFT JOIN #Table2 t2 ON t1.weeknumber=t2.weeknumber
不要注意我发布的所有其他代码,只是在那里创建临时表并在表格中插入值。
答案 1 :(得分:1)
你是在正确的轨道上,但只需要使用左连接。如果total为空,则NZ函数将置0。
SELECT Totals.Person, Weeks.WeekNo, Nz(Totals.total, 0) as TotalAmount
FROM Weeks LEFT JOIN Totals
ON (Weeks.WeekNo = Totals.weekno and Totals.Person = 'Bob');
编辑:您现在拥有的查询甚至不会给出您显示的结果,因为您遗漏了名称字段(这是一个字段的错误名称,因为它是一个保留字。)。你还没有提供所有的信息。此查询有效。
* 另一种方法:* 在Totals表上创建一个单独的查询,其中包含where子句:Name ='Bob'
Select Name, WeekNo, Total From Totals Where Name = 'Bob';
并将该查询替换为此查询中的Totals表。
Select b.Name, w.WeekNo, b.total
from Weeks as w
LEFT JOIN qryJustBob as b
on .WeekNo = b.WeekNo;
答案 2 :(得分:1)
SELECT b.Name, b.Week, b.Total
FROM Totals AS b
WHERE b.Name ='Bob'
UNION
SELECT 'Bob' AS Name, a.Week, 0 AS Total
FROM Weeks AS a
WHERE NOT EXISTS ( SELECT *
FROM Totals AS b
WHERE a.Week = b.Week
AND b.Name ='Bob' );