0

我有两个要加入的表。

表 A 有一列,名为“周”,包含 52 行:1、2、3、4、5、6 等。表 2 有三列,名为“名称”、“周”和“总”,并且包含 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

在此先感谢您的帮助!

4

3 回答 3

3

我知道它的访问权限,但您的加入不正确。这里我们进入 sql server.. 相同的概念只看连接条件:

--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

并从您的第一个表开始您的连接,并在 weeknumber 字段上左连接到您的第二个表。结果很简单:

SELECT t1.weeknumber as weeknumber, ISNULL(t2.total,0) as total FROM 
#Weeks t1 LEFT JOIN #Table2 t2 ON t1.weeknumber=t2.weeknumber

不要注意我发布的所有其他代码,它们只是用于创建临时表并将值插入表中。

于 2012-04-13T19:04:47.547 回答
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');

编辑:您现在的查询甚至不会给出您显示的结果,因为您遗漏了 Name 字段(这对于字段来说是一个错误的名称,因为它是一个保留字。)。您仍然没有提供所有信息。此查询有效。

*另一种方法:*在 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;
于 2012-04-13T19:20:15.070 回答
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' );
于 2012-04-16T10:01:22.423 回答