鉴于表:
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查询:
我希望结果如下:
| 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 ...)。
答案 0 :(得分:1)
我认为两个数据库中最好的方法看起来更像是这样:
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");
除了日期常量周围的引号外,此特定版本适用于两个数据库。
答案 1 :(得分:0)
您应该能够将逻辑更改为
Sum (case when male then 1 else 0) > 0
and
Sum (Case when female then 1 else 0) > 0
答案 2 :(得分:0)
感谢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
)