我有两张桌子:
prgm[id,name]
notes[id,note,id_prgm]
我实际上要求了解有关prgm的一些信息:
SELECT p.id, name, AVG(note), COUNT(note)
FROM notes n
JOIN prgm p
ON p.id=n.id_prgm
GROUP BY p.id
这项工作符合预期,但现在我想知道MAX
和AVG(note)
的{{1}},但如果我COUNT(note)
它会给我一个错误: MAX(COUNT(note))
。我理解为什么会有这个问题,但我不知道如何修复它。
我看到的唯一方法是做两个子请求并将其放在Invalid use of group function
内,但是有比两个子请求更好的方法吗?
(我在使用php的MySql上)
答案 0 :(得分:3)
最简单的答案是,
SELECT p.id, name, AVG(note), COUNT(note) totalCount
FROM notes n
INNER JOIN prgm p
ON p.id=n.id_prgm
GROUP BY p.id
ORDER BY totalCount DESC
LIMIT 1
但缺点是它不关心具有最高计数的重复记录。另一种选择是,
SELECT p.id, name, AVG(note), COUNT(note)
FROM notes n
INNER JOIN prgm p
ON p.id=n.id_prgm
GROUP BY p.id
HAVING COUNT(note) =
(
SELECT DISTINCT COUNT(note) totalCount
FROM notes n
INNER JOIN prgm p
ON p.id=n.id_prgm
GROUP BY p.id
ORDER BY totalCount DESC
LIMIT 1
)
答案 1 :(得分:0)
您可以对包含order by
和limit
的任一列执行此操作:
SELECT p.id, name, AVG(note), COUNT(note)
FROM notes n
JOIN prgm p
ON p.id=n.id_prgm
GROUP BY p.id
order by avg(note) desc
limit 1
要同时执行这两项操作,需要一些子查询。我会这样做:
select t.id, t.name, t.avgnote, t.countnote
from (select max(avgnote) as maxavg, max(countnote) as maxcount
from (SELECT p.id, name, AVG(note) as avgnote, COUNT(note) as countnote
FROM notes n
JOIN prgm p
ON p.id=n.id_prgm
GROUP BY p.id
) t
) themax join
(SELECT p.id, name, AVG(note) as avgnote, COUNT(note) as countnote
FROM notes n
JOIN prgm p
ON p.id=n.id_prgm
GROUP BY p.id
) t
on t.avgnote = themax.avgnote or t.countnote = themax.countnote
答案 2 :(得分:0)
这是包含一些testdata的数据库(与Access,MySQL和Oracle兼容):
CREATE TABLE notes (
id int NOT NULL,
note int NOT NULL,
id_prgm int NOT NULL
);
INSERT INTO notes (id, note, id_prgm) VALUES (1, 4, 1);
INSERT INTO notes (id, note, id_prgm) VALUES (3, 16, 1);
INSERT INTO notes (id, note, id_prgm) VALUES (4, 3, 2);
INSERT INTO notes (id, note, id_prgm) VALUES (5, 4, 2);
INSERT INTO notes (id, note, id_prgm) VALUES (6, 5, 2);
ALTER TABLE notes
ADD PRIMARY KEY (id);
CREATE TABLE prgm (
id int NOT NULL,
name varchar(255) NOT NULL
);
INSERT INTO prgm (id, name) VALUES (0, 'program 1');
INSERT INTO prgm (id, name) VALUES (1, 'program 1');
INSERT INTO prgm (id, name) VALUES (2, 'program 2');
ALTER TABLE prgm
ADD PRIMARY KEY (id);
您的查询:
SELECT p.id, name, AVG(note), COUNT(note)
FROM notes n
JOIN prgm p
ON p.id=n.id_prgm
GROUP BY p.id
返回这些记录:
id name AVG(note) COUNT(note)
1 program 1 10.0000 2
2 program 2 4.0000 3
如果您只想要AVG和COUNT列的MAX,请使用此查询:
select max(avg_note), max(count_note)
from (
SELECT AVG(note) as avg_note, COUNT(note) as count_note
FROM notes n, prgm p
WHERE p.id=n.id_prgm
GROUP BY p.id
) temptable
此查询也不兼容MySQL,但也与Access和Oracle兼容,因为我在FROM table1,table2 WHERE中更改了JOIN ON .. 我删除了SELECT中未包含在GROUP BY中的 name 字段。
由于性能/内存原因,我还在SELECT中删除了不必要的字段 p.id 。
查询将返回:
max(avg_note) max(count_note)
10.0000 3