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
此PostgreSQL查询分解了状态和顺序优先级的每种组合的记录数:
SELECT State_or_Province
, Order_Priority
, COUNT(*) tally
FROM SuperStore_Main
GROUP BY State_or_Province
, Order_Priority
;