Re: GROUP BY / HAVING - am I being thick?
От | Tom Lane |
---|---|
Тема | Re: GROUP BY / HAVING - am I being thick? |
Дата | |
Msg-id | 10966.955640265@sss.pgh.pa.us обсуждение исходный текст |
Ответ на | GROUP BY / HAVING - am I being thick? ("Andrew C.R. Martin" <a.c.r.martin@reading.ac.uk>) |
Список | pgsql-sql |
"Andrew C.R. Martin" <a.c.r.martin@reading.ac.uk> writes: > For each codon number, I want to obtain sum(nexamples) where expl = 'f'; > The following looks as though it should work according to "The > Practical SQL Handbook" (Bowman, Emerson & Darnovsky) > SELECT codon, sum(nexamples) > FROM summary > WHERE expl = 'f' > GROUP BY codon > HAVING expl = 'f'; Just drop the HAVING clause and that will work --- you're already filtering by expl at the WHERE stage, so there's no need to do it again after grouping (quite aside from the fact that you can't reference an ungrouped column in HAVING). The thing to remember about WHERE vs HAVING is that WHERE filters tuples before they are aggregated into groups, while HAVING filters afterwards. Whatever tuples get past the WHERE filter are collected into groups, and then HAVING is applied to the per-group output tuples to filter out whole groups that you don't want. In practice, you only need HAVING if you want to filter on aggregate functions of the groups. For instance, if in your example you didn't want to hear about codons with sum(nexamples) < 100, you'd do SELECT codon, sum(nexamples) FROM summary WHERE expl = 'f' GROUP BY codon HAVING sum(nexamples) >= 100; Once you realize that HAVING applies post-group, it should be pretty clear why the HAVING clause can only reference group-column values and aggregate results. Anything else is not well-defined at the group level. For instance, the group for codon=286 has several different values for nexamples, so you can't ask about a specific value of nexamples in the HAVING clause --- which one would you get? regards, tom lane
В списке pgsql-sql по дате отправления: