在postgresql上同时获取最大和最小总和值

dpiehjr4  于 2023-03-12  发布在  PostgreSQL
关注(0)|答案(1)|浏览(140)

我有表格:

TABLE A
Debtornum,debtor_name,debtor_svc_type,Has_Myaccount,debtor_class,debtor_email,debtor_svs_state,Do_Not_contact,account_status,payment_code
12345,John smith,B,Y,R,12345@gmail.com,CO,0,A,CSH
12346,John smith,B,Y,R,12346@yahoo.com,CO,1,F,autop*y
12347,Jane Smith,E,N,R,,MN,1,A,CSH
12348,Jane Smith,E,N,R,,MN,1,F,_recurpay

TABLE B
Debtornum,Premnum,invoice_nr,usage_mnthly_kwh,usage_rate
12345,3000001,100001,2.3,T19
12346,3000002,100002,2.2,T19
12347,3000003,100003,5.7,T33
12348,3000004,100004,34.7,T19

我想得到按类和帐户状态分组的总借方使用的最小值和最大值。
我试过了

select t.debtor_class, t.account_status, min(t.sum1), max(t.sum1) MaxUsage
FROM
(SELECT a.debtor_class, a.account_status, sum(b.usage_mnthly_kwh) sum1
FROM  debtor_table_a a
INNER JOIN usage_table_b b
ON a."Debtornum" = b."Debtornum"
GROUP BY a.debtor_class, a.account_status) t
group by t.debtor_class, t.account_status;

但是最小值和最大值是相同的-我做错了什么?

8gsdolmq

8gsdolmq1#

如果我没看错你的问题,你真正想要的是
1.首先获取每个(债务人、债务人_类、帐户_状态)中的债务人总使用情况
1.然后获取每个(debtor_class,account_status)中借方总使用量的最小值和最大值
考虑到这一点,provide查询在内部groupby条件中缺少“Debtornum”。
下面是获取所需结果的新查询:

select t.debtor_class, t.account_status, min(t.sum1), max(t.sum1) MaxUsage
FROM
(SELECT a.debtor_class, a.account_status, sum(b.usage_mnthly_kwh) sum1
FROM  debtor_table_a a
INNER JOIN usage_table_b b
ON a."Debtornum" = b."Debtornum"
GROUP BY a."Debtornum", a.debtor_class, a.account_status) t
group by t.debtor_class, t.account_status;

| 债务人类别|帐户状态|最小值|最大使用量|
| - ------|- ------|- ------|- ------|
| 右|A类|二、三|五、七|
| 右|F级|二、二|三十四点七|

相关问题