我有2张桌子,1张是Persons
,1张是Relationships
。
我想要找回孩子最多的人。
目前我正在加入这样的表:
SELECT
PERSONS.ID,
PERSONS.NATIVE_COUNTRY,
RELATIONSHIPS.PERSON_ID,
RELATIONSHIPS.RELATION
FROM PERSONS
INNER JOIN RELATIONSHIPS ON RELATIONSHIPS.PERSON_ID = ID
AND RELATIONSHIPS.RELATION = 'child';
现在我正在尝试计算PERSONS.ID
并获得最大值,但不知道该怎么做。
答案 0 :(得分:3)
你可以使用分区......
SELECT PERSONS.ID, PERSONS.NATIVE_COUNTRY, RELATIONSHIPS.PERSON_ID,
RELATIONSHIPS.RELATION,
count(*) over (partition by Persons.ID order by Persons.ID)
FROM PERSONS
INNER JOIN RELATIONSHIPS ON RELATIONSHIPS.PERSON_ID = ID AND
RELATIONSHIPS.RELATION = 'child';
另外,如果你不喜欢
分区,你可以做简单的GROUP BYSELECT PERSONS.ID, PERSONS.NATIVE_COUNTRY, RELATIONSHIPS.PERSON_ID,
RELATIONSHIPS.RELATION,
COUNT(*)
FROM PERSONS
INNER JOIN RELATIONSHIPS ON RELATIONSHIPS.PERSON_ID = ID AND
RELATIONSHIPS.RELATION = 'child';
GROUP BY PERSONS.ID, PERSONS.NATIVE_COUNTRY, RELATIONSHIPS.PERSON_ID,
RELATIONSHIPS.RELATION
此外,使用连接时尝试使用别名,它的可读性更好,没有理由使用大写字符
答案 1 :(得分:0)
您可以尝试使用group by:
SELECT PERSONS.ID, COUNT(*) "No of Children" FROM PERSONS
INNER JOIN RELATIONSHIPS ON RELATIONSHIPS.PERSON_ID = ID
AND RELATIONSHIPS.RELATION = 'child'
GROUP BY persons.id;