[Postgres] Group and Aggregate Data in Postgres

本文介绍如何使用PostgreSQL的CASE语句进行电影数据的类别转换,并通过GROUP BY进行数据聚合,以统计不同类别的电影数量。

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;

 

转载于:https://www.cnblogs.com/Answer1215/p/6532739.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值