我有一个表“Customers”,其中包含 CustomerID
、MainCountry
和 CustomerTypeID
列。
我有 5 种客户类型 1,2,3,4,5 。
我想根据客户类型统计每个国家/地区的客户数量。我正在使用以下查询:
select count(CustomerID) as CustomerCount,MainCountry,CustomerTypeID
from Customers
group by CustomerTypeID,MainCountry
但有些国家/地区没有任何类型 1、2、3、4 或 5 下的客户。
因此,如果该国家/地区不存在客户类型,我想设置默认值 0。
目前提供的数据如下:-
CustomerCount MainCountry CustomerTypeID
5695 AU 1
525 AU 2
12268 AU 3
169 AU 5
18658 CA 1
1039 CA 2
24496 CA 3
2259 CA 5
2669 CO 1
10 CO 2
463 CO 3
22 CO 4
39 CO 5
由于“AU”没有类型 4,所以我想要一个默认值。
最佳答案
您应该将您的表与具有 TypeId 的表连接起来。在这种情况下
select count(CustomerID) as CustomerCount,TypeTable.MainCountry,TypeTable.TId
from
Customers
RIGHT JOIN (
select MainCountry,TId from
(
select Distinct MainCountry from Customers
) as T1,
(
select 1 as Tid
union all
select 2 as Tid
union all
select 3 as Tid
union all
select 4 as Tid
union all
select 5 as Tid
) as T2
) as TypeTable on Customers.CustomerTypeID=TypeTable.TId
and Customers.MainCountry=TypeTable.MainCountry
group by TypeTable.TId,TypeTable.MainCountry
关于sql查询按客户类型获取数据组,如果找不到客户类型需要添加默认值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19403088/