Postgresql - 先group 然后根据不同group,用同一行 不同列展示

With 
--1. group
aTable as(
	SELECT 
	"SourceOrderNumber","OperateType",sum("ServiceCatagoryQuota") as "ServiceCatagoryQuota", array_agg("UsedOrderItemNumber") as  "UsedOrderItemNumber"
	FROM orders."a" 
	group by "SourceOrderNumber","OperateType"
),
--2. group后 按类型 一行展示
aSplitTable as (
   select "SourceOrderNumber",
   sum(CASE "OperateType" WHEN 0 THEN "ServiceCatagoryQuota" ELSE 0 END ) "RechargeQuota", 
   sum(CASE "OperateType" WHEN 1 THEN "ServiceCatagoryQuota" ELSE 0 END ) "ConsumeQuota",
   sum(CASE "OperateType" WHEN 3 THEN "ServiceCatagoryQuota" ELSE 0 END ) "RechargeReturnQuota",
   sum(CASE "OperateType" WHEN 2 THEN "ServiceCatagoryQuota" ELSE 0 END ) "CancelConsumeQuota",
   sum("ServiceCatagoryQuota") as "LeftQuota"
   from aTable
   group by "SourceOrderNumber"
)
SELECT * from aSplitTable;

  

case的其他用法

SELECT 
po."OrderNumber" as "订单编号",
po."Currency" as "币种id",
CASE WHEN sc."Currency" =1 THEN 'CNY'
     WHEN sc."Currency" =2 THEN 'USD'
     WHEN sc."Currency" =3 THEN 'EUR'
     WHEN sc."Currency" =4 THEN 'HKD'
     WHEN sc."Currency" =5 THEN 'GBP'
     WHEN sc."Currency" =6 THEN 'AUD'
     WHEN sc."Currency" =7 THEN 'CAD'
     WHEN sc."Currency" =8 THEN 'JPY'
     WHEN sc."Currency" =9 THEN 'KRW'
     WHEN sc."Currency" =10 THEN 'NZD'
     WHEN sc."Currency" =11 THEN 'RUB'
     WHEN sc."Currency" =12 THEN 'SGD'
     ELSE '其他' end
AS "币种名称"
from po 
limit 10;

  

上一篇:postgresql 异步创建索引


下一篇:2022牛客寒假算法基础集训营5