原始問題:確定,對于只與 30 歲以上女性結婚的所有總統,他們所有婚姻中的身份證和子女總數?
問題:問題是pres_id 44有三列,有3個不同的總統,他們的妻子有些低于和高于30,我怎么能只顯示一個不包含重復值(pres_id)的pres_id,并且save_age應該總是更大超過30?
SELECT pres_id, SUM(nr_children) as sumChild
FROM pres_marriage pm
WHERE spouse_age > 30
GROUP BY pres_id
HAVING SUM(nr_children) >= 1
ORDER BY pres_id
當前結果:
pres_id sumChild
23 3
32 1
42 2
44 1
預期結果:
pres_id sumchild
23 3
32 1
42 2
uj5u.com熱心網友回復:
如果您只想要那些只與 30 歲以上的配偶結婚的總統,這意味著特定總統的配偶最低年齡超過 30 歲。
所以你可以把它放在現有的“有”子句中。這應該適合你:
SELECT
pres_id, SUM(nr_children) as sumChild
FROM
pres_marriage pm
GROUP BY
pres_id
HAVING
SUM(nr_children) >= 1
AND
min(spouse_age) > 30
ORDER BY
pres_id
uj5u.com熱心網友回復:
您可以排除不適合的結果。可以通過將同一個表與另一個標準連接起來來進行排除。在你的情況下我會怎么做。第一次建立另一個表:
SELECT pres_id, SUM(spouse_age) as youngSpouse
FROM pres_marriage pm
WHERE spouse_age < 31
GROUP BY pres_id
2nd 加入兩個表,并添加另一個 where 子句:
SELECT pres_id, SUM(nr_children) as sumChild
FROM pres_marriage pm
LEFT JOIN ( SELECT pres_id as pres_id2 , SUM(spouse_age) as youngSpouse
FROM pres_marriage pm
WHERE spouse_age < 31
GROUP BY pres_id ) ON pres_id = pres_id2
WHERE spouse_age > 30 AND youngSpouse is NULL
GROUP BY pres_id
HAVING SUM(nr_children) >= 1
ORDER BY pres_id
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/511356.html
