2

我有一个“客户”表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,所以我想要一个默认值。

4

3 回答 3

3

您应该将您的表与带有 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
于 2013-10-16T12:19:55.530 回答
2
Select Country.MainCountry, CustomerType.CustomerTypeId, Count(T.CustomerID) As CustomerCount
From   (Select Distinct MainCountry From Customers) As Country
       Cross Join (Select Distinct CustomerTypeId From Customers) As CustomerType
       Left Join Customers T
         On Country.MainCountry = T.MainCountry
         And CustomerType.CustomerTypeId = T.CustomerTypeId
             -- Edit here
             And T.CreatedDate > Convert(DateTime, '1/1/2013')
             -- End Edit
Group By Country.MainCountry, CustomerType.CustomerTypeId
Order By MainCountry, CustomerTypeId
于 2013-10-16T12:24:23.807 回答
0

试试看:

与国家为 (
从客户中选择不同的 MainCountry
),
客户类型为 (
(从客户中选择不同的 CustomerTypeId
),
映射为 (
从国家选择 MainCountry、CustomerTypeId、CustomerType
)

选择 count(CustomerID) 作为 CustomerCount,a.MainCountry,a.CustomerTypeID
从
在 a.CustomerCount=b.CustomerCount 和 a.CustomerTypeID=b.CustomerTypeID 上映射 a 左连接客户 b

于 2013-10-16T14:52:01.427 回答