首页 > 代码库 > [Postgres] Group and Aggregate Data in Postgres
[Postgres] Group and Aggregate Data in Postgres
How can we see a histogram of movies on IMDB with a particular rating? Or how much movies grossed at the box office each month? Or how many movies there are of each genre? These are examples of data aggregation questions, and this lesson will teach us how to answer them.
In the table we have ‘action‘, ‘animation‘... ‘short‘ categories. They all use ‘true‘ of ‘false‘.
What if we want to use those by its categoreis not just ture of false?
We can use ‘CASE‘ in Postgres.
SELECT CASE WHEN action=true THEN ‘action‘ WHEN animation=true THEN ‘animation‘ WHEN comedy=true THEN ‘comedy‘ WHEN drama=true THEN ‘drama‘ WHEN short=true THEN ‘short‘ ELSE ‘other‘END AS genre,titleFROM moviesLIMIT 100
And now we want to get "how many movies for each category" from previous result.
What we can do is using "GROUP BY" and "WITH":
WITH genres AS( SELECT CASE WHEN action=true THEN ‘action‘ WHEN animation=true THEN ‘animation‘ WHEN comedy=true THEN ‘comedy‘ WHEN drama=true THEN ‘drama‘ WHEN short=true THEN ‘short‘ ELSE ‘other‘ END AS genre, title FROM movies LIMIT 100) SELECT genre,COUNT(*)FROM genresGROUP BY genre;
[Postgres] Group and Aggregate Data in Postgres
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。