我有一个访问数据库中的几个表:选择查询加入两个字段?
ID | LocationName
1 | Location1
2 | Location2
ID | LocationID | Date | NumProductsDelivered
1 | 1 | 12/10 | 3
2 | 1 | 01/11 | 2
3 | 1 | 02/11 | 2
4 | 2 | 11/10 | 1
5 | 2 | 12/10 | 1
ID | LocationID | Date | NumEmployees | EmployeeType
1 | 1 | 12/10 | 10 | 1 (=Permanent)
2 | 1 | 12/10 | 3 | 2 (=Temporary)
3 | 1 | 12/10 | 1 | 3 (=Support)
4 | 2 | 10/10 | 1 | 1
5 | 2 | 11/10 | 2 | 1
6 | 2 | 11/10 | 1 | 2
7 | 2 | 11/10 | 1 | 3
8 | 2 | 12/10 | 2 | 1
9 | 2 | 12/10 | 1 | 3
我想要做的就是在LocationID作为参数传递,并取回东西如下表等。所以,如果我在2传我的LocationID,我应该得到:
Date | NumProductsDelivered | NumPermanentEmployees | NumSupportEmployees
10/10 | | 1 |
11/10 | 1 | 2 | 1
12/10 | 1 | 2 | 1
看起来这应该是一个非常简单的查询。我甚至不需要第一个表格,除非填写用户选择他们想要报告的位置的表单上的组合框。不幸的是,我所做的一切都让我得到了比我应得的更多的数据。我的困惑在于如何设置连接(大概是我在这里寻找的),因为我希望date和locationID对结果集中的每一行都是相同的。
任何帮助将不胜感激。
谢谢。
编辑: 好 - 答案下面也不太工作,但它确实让我在正确的轨道上,我能够使用以下查询:
SELECT t1.Date, t2.NumProductsDelivered,
(SELECT t1a.NumEmployees
FROM table3 t1a
WHERE t1a.EmployeeType=1 AND t1a.LocationID=t1.LocationID AND t1a.Date= t1.Date)
AS "PermEmps",
(SELECT t1b.NumEmployees
FROM table3 t1b
WHERE t1b.EmployeeType=3 AND t1b.LocationID=t1.LocationID AND t1b.Date=t1.Date)
AS "SupportEmps"
FROM table3 AS t1 LEFT JOIN table2 AS t2 ON (t2.Date=t1.Date)
AND (t2.LocationID=t1.LocationID)
WHERE t1.LocationID=2
GROUP BY t1.Date, t1.LocationID, t2.NumProductsDelivered;
这让我我正在寻找的结果。但是,如果产品交付地点有中断,我看不到正确的结果。看起来,只要有空行,记录就会停下来,然后再从头回来。所以,在这里我可能会看到这一点:
Date | NumProductsDelivered | NumPermanentEmployees | NumSupportEmployees
10/10 | | 1 |
11/10 | 1 | 2 | 1
12/10 | 1 | 2 | 1
01/10 | 2 | | 1
06/10 | 1 | |
我只看到这一点:
Date | NumProductsDelivered | NumPermanentEmployees | NumSupportEmployees
10/10 | | 1 |
11/10 | 1 | 2 | 1
12/10 | 1 | 2 | 1
01/10 | 2 | | 1
你不应该GROUP BY t1.LocationID因为你没有选择它,它始终是2。我也要推荐使用比“t1”更好的名字来表示可读性。另一个问题是一个谜题...... t1和t2之间是否存在1对1的关系?另外,尝试删除join和subselect以查看是否全部获取您需要的日期(我会在下面添加到我的答案中) – 2010-04-30 20:04:29