mysql - SQL:如何获得列中不同值的总数?
问题描述
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 中:
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
推荐阅读
- java - 我可以让 maven 使用这个包结构运行吗?我应该如何改变它?
- scala - 使用 @ 指定 Scala 形式的电子邮件
- assembly - 尝试编写准系统 64 位内核时“重定位被截断以适应”
- python - 斐波那契数列之和的代码没有给出正确的和
- ssas - 分区数据与数据源视图
- r - 如何计算每行数据集中唯一元素的存在并将它们列出在r中
- drupal - 在 drupal 8 安装上呈现实体字段标记
- dns - 为什么 `getaddrinfo` 不支持别名?
- python - 在 Python 中更新 CSV 文件
- javascript - 哪种方式最适合 React Native 中的条件渲染?