2
SELECT DISTINCT( m.pm_name ) 
FROM   prime_minister AS m, 
       prime_minister AS p 
WHERE  m.state_born IS NOT NULL 
GROUP  BY m.pm_name, 
          m.birth_yr 
HAVING m.birth_yr = (SELECT Min(p.birth_yr) 
                     FROM   prime_minister) 

我的问题如下:

该查询应该会产生第一位出生在澳大利亚某个州的总理......因此WHERE m.state_born IS NOT NULL

4

5 回答 5

1

为什么要在子查询中引用外部表?像这样写一个简单的子查询。

SELECT DISTINCT pm_name 
FROM prime_minister 
WHERE state_born IS NOT NULL 
AND birth_yr = (SELECT MIN(birth_yr) FROM prime_minister)
于 2013-03-21T10:47:43.660 回答
0

Not sure I understand your question completely. But I don't see the reason for a group by or having at all:

SELECT m.pm_name
FROM   prime_minister
WHERE  m.state_born IS NOT NULL 
AND    m.birth_yr = (SELECT Min(p.birth_yr) 
                     FROM   prime_minister p
                     WHERE  p.state_born IS NOT NULL) 
于 2013-03-21T10:52:42.853 回答
0

这行得通吗?

SELECT TOP 1 pm_name, MIN(birth_yr)
FROM   prime_minister
WHERE  birth_yr IS NOT NULL 
GROUP BY pm_name
ORDER BY pm_name, MIN(birth_yr)
于 2013-03-21T10:54:36.193 回答
0

使用 EXISTS() 运算符尝试选项

SELECT m.pm_name
FROM prime_minister AS m     
WHERE EXISTS (
              SELECT 1
              FROM prime_minister p
              WHERE p.state_born IS NOT NULL
              HAVING MIN(p.birth_yr) = m.birth_yr
              ) AND m.state_born IS NOT NULL
于 2013-03-21T12:22:06.720 回答
0

我认为您正在尝试找到每个州出生的第一位总理:

select pm_name, state_born from prime_minister m
inner join 
(
    select min(birth_yr) birth_yr, state_born
    from prime_minister
    where state_born is not null
    group by state_born
)
t
on m.state_born = t.state_born and m.birth_yr = t.birth_yr
于 2013-03-21T11:07:53.477 回答