我有很多团体。每个组条目由另一个组条目拥有。例如,soccer club
组拥有soccer training
,soccer cardio squad
,pro training
和beginner training
。我想找出哪个组拥有最多的training
类型组。为了确定哪个组属于彼此,我有一个名为groupOwnedBy()
的函数,该函数返回拥有该组的id
组。
例如,如果我们要检查哪个组拥有soccer training
,我们传入2
,因为这是soccer training
的ID
SELECT * FROM groupOwnedBy(2);
将返回拥有1
的组soccer training
的ID(表示它是soccer club
所拥有的)
groupOwnedBy
------------
1
SELECT * from groupOwnedBy(1); -- will return 1. soccer club is owned by soccer club
我要打印拥有最多训练类型组的组的名称。在这种情况下,它应该打印soccer club
。
CREATE TABLE groups (
id integer primary key,
type text NOT NULL,
name text
);
INSERT INTO groups (id, type, name) VALUES
(1, 'owner', 'soccer club'), -- owned by soccer club
(2, 'training', 'soccer training'), -- owned by soccer club
(3, 'cardio', 'soccer cardio squad'), -- owned by soccer club
(4, 'training', 'pro training'), -- owned by soccer club
(5, 'training', 'beginner training'), -- owned by soccer club
(6, 'cardio', 'Cricket cardio team'), -- owned by cricket club
(7, 'owner', 'Cricket club'), -- owned by cricket club
(8, 'training', 'Cricket training'), -- owned by cricket club
(9, 'owner', 'Hockey club'), -- owned by Hockey club
(10, 'owner', 'Kids Hockey') -- owned by Hockey club
(11, 'training', 'smart train'), -- owned by Hockey club
(12, 'training', 'fit train'); -- owned by Hockey club
我尝试过
SELECT name
FROM group
WHERE type = 'training'
GROUP BY ownedByGroup(id)
ORDER BY COUNT(*) DESC
LIMIT 1;
但我不断收到错误消息:
ERROR: column "name" must appear in the GROUP BY clause or be used in an aggregate function
答案 0 :(得分:0)
您将按ownerByGroup(id)表达式分组并获得最大计数(*)。
之后,您将与组表联接,以便按照以下方式查找与id对应的名称
select y.name,y.id
from (
SELECT ownedByGroup(id) as max_training_grp_id
,count(*)
FROM group
WHERE type = 'training'
GROUP BY ownedByGroup(id)
ORDER BY COUNT(*) DESC
LIMIT 1
)x
join group y
on x.max_training_grp_id=y.id