我有一个表currency
,paymenttype
和invoiceamount
。我必须写一个查询来获取currency
,paymenttype
并invoiceamount
完成。
这对于 group by 来说非常简单。但实际上我有3种支付类型——0、1、2。表中的数据是
Currency PaymentType Invoice Amount
Aaa. 0. 100
Aaa. 1. 200
Aaa. 1. 50
Bbb. 0. 150
Bbb. 1. 100
Bbb. 2. 100
Run Code Online (Sandbox Code Playgroud)
我的查询是
Select currency, paymenttype, sum(invoiceamount) as total
from table
group by currency, paymenttype
Run Code Online (Sandbox Code Playgroud)
结果
Currency paymenttype total
Aaa. 0. 100
Aaa. 1. 250
Bbb. 0. 150
Bbb. 1. 100
Bbb. 2. 100
Run Code Online (Sandbox Code Playgroud)
作为Aaa。没有paymenttype
2 它也应该显示一个值为 0 的行,如下所示。
Aaa. 2. 0
Run Code Online (Sandbox Code Playgroud)
这该怎么做?
如果付款类型和货币列表已知,您可以使用 CTE 执行此操作。
with paymenttypes as (
select 0 as ptype,
Union select 1 as ptype,
Union select 2 as ptype ),
currencies as
( select 'Aaa' as currency
union
select 'Bbb' as currency ),
sourcedata as (
select currency, ptype as paymenttype, 0 as amount
from currencies, paymenttypes
Union all
select *
from data)
select currency, paymenttype, sum(amount)
from sourcedata
group by currency, paymenttype;
Run Code Online (Sandbox Code Playgroud)
它基本上创建了所有货币的笛卡尔积,paymenttype 对的金额为 0,然后将其与源数据连接起来。
如果您的付款类型和货币列表都在查找表中,请将其替换。
另请注意,还有其他方法,使用COALESCE
等。
归档时间: |
|
查看次数: |
615 次 |
最近记录: |