我将非常感谢帮助找到如何使用WHERE和IN作为要求组合/加入两个简单SQL查询的方法。
简单地说,我想要这个查询的结果:
SELECT Nationality, MAX(ActorName) as Oldest,
FROM ACTOR
WHERE BirthDate IN
(SELECT MIN(BirthDate) as MinBday FROM ACTOR GROUP BY Nationality)
GROUP BY Nationality
结果如下:
+------------+--------------+
| nationality| oldest |
+------------+--------------+
| american | brad pitt |
+------------+--------------+
| british | pierce bro |
+------------+--------------+
| italian | monica bellu |
+------------+--------------+
加入此查询的结果:
SELECT Nationality, MAX(ActorName) as Oldest,
FROM ACTOR
WHERE BirthDate IN
(SELECT MAX(BirthDate) as MinBday FROM ACTOR GROUP BY Nationality)
GROUP BY Nationality
结果如下:
+------------+--------------+
| nationality| youngest |
+------------+--------------+
| american | angelina j |
+------------+--------------+
| british | jason stat |
+------------+--------------+
| italian | paul gia |
+------------+--------------+
为了得到如下结果表:
+------------+--------------+--------------+
|nationality | oldest | youngest |
+------------+--------------+--------------+
| american | brad pitt | angelina j |
+------------+--------------+--------------+
| british | pierce bro | jason stat |
+------------+--------------+--------------+
| italian | monica bellu | paul gia |
+------------+--------------+--------------+
注意:对于最早的出生日期,2个查询之间的唯一区别是 MIN (出生日期),而对于最年初的出生日期, MAX (出生日期)。
答案 0 :(得分:0)
您可以获得生日,并可以直接加入
SELECT a.Nationality, MAX(a.ActorName) as Oldest,
FROM ACTOR a
JOIN (SELECT Nationality,
MIN(BirthDate) as MinBday,
MAX(BirthDate) as MaxBday
FROM ACTOR
GROUP BY Nationality) xxx
ON a.Nationality = xxx.Nationality
AND (a.BirthDate = xxx.MinBday OR a.BirthDate = xxx.MaxBday)
GROUP BY Nationality;
答案 1 :(得分:0)
一个非常丑陋的sql可以跟随,而不是最有效的,只是一种方法。
SELECT
t1.Nationality, t1.Oldest, t2.youngest
FROM (
SELECT Nationality, MAX(ActorName) as Oldest -- ,
FROM ACTOR
WHERE BirthDate IN
(SELECT MIN(BirthDate) as MinBday FROM ACTOR GROUP BY Nationality)
GROUP BY Nationality
) t1
JOIN (
SELECT Nationality, MAX(ActorName) as youngest
FROM ACTOR
WHERE BirthDate IN
(SELECT MAX(BirthDate) as MaxBday FROM ACTOR GROUP BY Nationality)
GROUP BY Nationality
) t2 ON t1.Nationality = t2.Nationality
或试试这个(未经测试):
SELECT
Nationality,
MAX(CASE WHEN BirthDate = t1.MinBday THEN ActorName ELSE NULL END) as Oldest,
MAX(CASE WHEN BirthDate = t1.MaxBday THEN ActorName ELSE NULL END) as youngest
FROM ACTOR
JOIN (
SELECT Nationality, MIN(BirthDate) as MinBday, MAX(BirthDate) as MaxBday
FROM ACTOR GROUP BY Nationality) t
ON ACTOR.Nationality = t.Nationality
GROUP BY Nationality