zoukankan      html  css  js  c++  java
  • [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,
    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;

  • 相关阅读:
    2018/12/08 L1-043 阅览室 Java
    2018/12/08 L1-042 日期格式化 Java
    breeze源码阅读心得
    Spark ML源码分析之四 树
    Spark ML源码分析之三 分类器
    Spark ML源码分析之二 从单机到分布式
    Spark ML源码分析之一 设计框架解读
    Adaboost的意义
    RBM如何训练?
    ChromeTimeline
  • 原文地址:https://www.cnblogs.com/Answer1215/p/6532739.html
Copyright © 2011-2022 走看看