访问sql查询连接匹配有两个匹配的连接行
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了访问sql查询连接匹配有两个匹配的连接行相关的知识,希望对你有一定的参考价值。
给定表:
tblGuardian
| ID | FirstName | LastName |
|----|-----------|----------|
| 1 | Sam | Smith |
| 2 | John | Jones |
| 3 | Jack | Black |
| 4 | Jane | Doe |
tblChild
| ID | FirstName | LastName | Sex | DOB | GuardianID |
|----|-----------|----------|-----|----------------------|------------|
| 1 | Sara | Smith | F | 2010-01-01T00:00:00Z | 1 |
| 2 | Dave | Smith | M | 2008-03-01T00:00:00Z | 1 |
| 3 | Mike | Jones | M | 2009-06-01T00:00:00Z | 2 |
| 4 | Fred | Jones | M | 2010-07-01T00:00:00Z | 2 |
| 5 | Sally | Black | F | 2011-11-01T00:00:00Z | 3 |
| 6 | Harry | Doe | M | 2007-07-01T00:00:00Z | 4 |
| 7 | Kate | Doe | F | 2008-04-01T00:00:00Z | 4 |
Access sql查询将返回什么:
- 所有监护人和他们孩子的DOB
- 至少有一个女性和一个男性的孩子
我希望结果看起来像:
| Firstname | LastName | Child FirstName | DOB |
|-----------|----------|-----------------|------------|
| Sam | Smith | Sara | 2010-01-01 |
| Sam | Smith | Dave | 2008-03-01 |
| Jane | Doe | Harry | 2007-07-01 |
| Jane | Doe | Kate | 2008-04-01 |
我有这个MS SQL查询工作:
SELECT g1.FirstName, g1.LastName, c1.FirstName, c1.DOB FROM
tblGuardian g1 INNER JOIN tblChild c1 ON g1.ID = c1.GuardianID
WHERE g1.ID in (
SELECT g.ID
FROM tblGuardian g INNER JOIN tblChild c ON c.GuardianID = g.ID
GROUP BY g.ID
HAVING Count(Distinct c.Sex) = 2
)
我现在需要将其转换为MS Access!
Access SQL不接受Count(Distinct ...)。
答案
我认为两个数据库中最好的方法看起来更像是这样的:
SELECT g.FirstName, g.LastName, c.FirstName, c.DOB
FROM tblGuardian as g INNER JOIN
tblChild as c
ON g.ID = c.GuardianID
WHERE EXISTS (SELECT 1 FROM tblChild as c2 WHERE c2.GuardianID = g.ID AND c2.Sex = "F") AND
EXISTS (SELECT 1 FROM tblChild as c2 WHERE c2.GuardianID = g.ID AND c2.Sex = "M");
除了日期常量周围的引号外,此特定版本将适用于两个数据库。
另一答案
感谢Pham X.Bach,有效的解决方案是:
SELECT g1.FirstName, g1.LastName, c1.FirstName, c1.DOB FROM
tblGuardian g1 INNER JOIN tblChild c1 ON g1.ID = c1.GuardianID
WHERE g1.ID in (
SELECT g.ID
FROM tblGuardian g INNER JOIN tblChild c ON c.GuardianID = g.ID
GROUP BY g.ID
HAVING SUM(IIF(c.Sex="M",1,0))>0 AND SUM(IIF(c.Sex="F",1,0))>0
)
另一答案
您应该能够将逻辑更改为某些内容
Sum (case when male then 1 else 0) > 0
and
Sum (Case when female then 1 else 0) > 0
以上是关于访问sql查询连接匹配有两个匹配的连接行的主要内容,如果未能解决你的问题,请参考以下文章