【问题标题】:SQL: How would I get a total count for distinct values in a column?SQL:如何获得列中不同值的总数?
【发布时间】:2020-04-03 22:33:02
【问题描述】:

这里是 SQL 初学者。目前正在解决 mySQL 和 Postgre SQL 的问题。

我想获得每个订单优先级的总计数(Not_Specified、Low、Medium、High、Critical) 对于每个州。

例如,我想为德克萨斯州获取一列,其中每个订单优先级类别都有一个数字,然后为下一个州提供一个数字,依此类推。每个订单优先级在每个州都有自己的计数列。

这是我当前的以下查询。我可以使用子查询还是需要使用窗口函数?

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 

【问题讨论】:

标签: mysql sql postgresql group-by pivot


【解决方案1】:

您似乎在寻找条件聚合。

在 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

在 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

【讨论】:

    【解决方案2】:

    此 PostgreSQL 查询按状态和顺序优先级的每种组合细分记录计数:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-08-27
      相关资源
      最近更新 更多