简体   繁体   English

SQL:如何获得列中不同值的总数?

[英]SQL: How would I get a total count for distinct values in a column?

SQL Beginner here. SQL 初学者在这里。 Currently working on a problem with mySQL and Postgre SQL.目前正在解决 mySQL 和 Postgre SQL 的问题。

I'd like to get a total count for each order priority (Not_Specified, Low, Medium, High, Critical) for each state.我想获得每个 state 的每个订单优先级(Not_Specified、Low、Medium、High、Critical)的总数。

For example, I'd like to get a column for Texas with a number for each order priority category, and then one for the next state, and so on.例如,我想为德克萨斯州获取一列,其中每个订单优先级类别都有一个数字,然后为下一个 state 获取一个数字,依此类推。 Each order priority would have its own column of count per state.根据 state,每个订单优先级都有自己的计数列。

This is my current query below.这是我下面的当前查询。 Can I use a subquery or do I need to use a window function?我可以使用子查询还是需要使用 window function?

SELECT 
    Customer_ID, City, State_or_Province, Order_Date, Order_Priority, 
    ROW_NUMBER() OVER(ORDER BY City ASC, State_or_Province ASC) AS Row_N,
    COUNT(Order_Priority) OVER (Partition BY State_or_Province) AS State_Total_count

FROM SuperStore_Main 

在此处输入图像描述

You seem to be looking for conditional aggregation.您似乎正在寻找条件聚合。

In MySQL:在 MySQL 中:

select
    state_or_province,
    sum(order_priority = 'Not_Specified') cnt_not_specified,
    sum(order_priority = 'Low')           cnt_low
    sum(order_priority = 'Medium')        cnt_medium
    sum(order_priority = 'High')          cnt_not_high
    sum(order_priority = 'Critical')      cnt_critical
from superstore_main
group by state_or_province

In Postgres:在 Postgres 中:

select
    state_or_province,
    count(*) filter(where order_priority = 'Not_Specified') cnt_not_specified,
    count(*) filter(where order_priority = 'Low')           cnt_low
    count(*) filter(where order_priority = 'Medium')        cnt_medium
    count(*) filter(where order_priority = 'High')          cnt_not_high
    count(*) filter(where order_priority = 'Critical')      cnt_critical
from superstore_main
group by state_or_province

This PostgreSQL query breaks down the record count by each combination of state and order priority:此 PostgreSQL 查询按 state 和订单优先级的每个组合细分记录计数:

  SELECT State_or_Province
       , Order_Priority
       , COUNT(*) tally
    FROM SuperStore_Main 
GROUP BY State_or_Province
       , Order_Priority
       ;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM