码迷,mamicode.com
首页 > 其他好文 > 详细

[Postgres] Group and Aggregate Data in Postgres

时间:2017-03-10 20:52:34      阅读:228      评论:0      收藏:0      [点我收藏+]

标签:logs   previous   man   oss   ros   http   image   action   case   

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,
title
FROM movies
LIMIT 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 genres
GROUP BY genre;

技术分享

 

[Postgres] Group and Aggregate Data in Postgres

标签:logs   previous   man   oss   ros   http   image   action   case   

原文地址:http://www.cnblogs.com/Answer1215/p/6532739.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!