开发者

Nested group by

开发者 https://www.devze.com 2023-02-06 00:12 出处:网络
I have a table that contains ages of people and a group they are in, but sometimes the group is not present.

I have a table that contains ages of people and a group they are in, but sometimes the group is not present.

I would like to get a total age per group, but if the group data is missing then I would like the name of the person and their age.

It is almost like a nested group. I 开发者_开发百科want to group by the group name first, but if it isn't present then group by individual's name.

I hope that makes some sense! Any help greatly appreciated.


You might try a union...

SELECT Group, sum(Age)
FROM People
WHERE Group > ''
GROUP by Group
UNION SELECT PersonName, Age FROM People WHERE Group is null

0

精彩评论

暂无评论...
验证码 换一张
取 消