我有这张桌子:
Docenza(id, id_facolta, ..., orelez)
Facolta(id, ...)
我想为每个facolta都获取完成最大orelez数量和orelez数量的Docenza的ID:
id_docenzaP facolta1 max(orelez)
id_docenzaQ facolta2 max(orelez)
...
id_docenzaZ facoltaN max(orelez)
我该怎么做?这就是我要做的:
SELECT DISTINCT ... F.nome, SUM(orelez) AS oreTotali
FROM Docenza D
JOIN Facolta F ON F.id = D.id_facolta
GROUP BY F.nome
我得到类似的东西
docenzaP facolta1 maxValueForidP
docenzaQ facolta1 maxValueForidQ
...
docenzaR facolta2 maxValueForidR
docenzaS facolta2 maxValueForidS
...
docenzaZ facoltaN maxValueForFacoltaN
我怎样才能仅取每个facolta的最大值?
答案 0 :(得分:0)
大概是您想要的:
SELECT F.nome, sum(orelez) AS oreTotali
FROM Docenza D JOIN
Facolta F
ON F.id = D.id_facolta
GROUP BY F.nome;
我不确定SELECT DISTINCT
应该做什么。它几乎从未与GROUP BY
一起使用。 . . .
建议您选择其他列,这些列对于您想要的结果是不需要的。
答案 1 :(得分:0)
这是未经测试的,并且由于您没有提供具有预期结果的样本数据,因此我无法确定它确实是您所需要的。
这有点难看,我敢肯定有一些聪明的相关子查询方法,但是我从来都不擅长这些。
SELECT st.focolta,
s_orelez,
TMP3.id_docenza
FROM some_table AS st
INNER
JOIN (SELECT *
FROM (SELECT focolta,
s_orelez,
id_docenza,
ROW_NUMBER() OVER -- Get the ranking of the orelez sum by focolta.
( PARTITION BY focolta
ORDER BY s_orelez DESC
) rn_orelez
FROM (SELECT focolta,
id_docenza,
SUM(orelez) OVER -- Sum the orelez by focolta
( PARTITION BY focolta
) AS s_orelez
FROM some_table
) TMP
) TMP2
WHERE = TMP2.rn_orelez = 1 -- Limit to the highest rank value
) TMP3
ON some_table.focolta = TMP3.focolta; -- Join to focolta to the id associated with the hightest value.