sql查询按客户类型获取数据组,如果找不到客户类型,则需要添加默认值

时间:2013-10-16 12:13:28

标签: sql sql-server

我的表格为“客户”,其中包含CustomerIDMainCountryCustomerTypeID列。

我有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所以我想要一个默认值。

3 个答案:

答案 0 :(得分: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

答案 1 :(得分: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

答案 2 :(得分:0)

试试:

with cuntry as (
Select Distinct MainCountry From Customers
),
CustomerType as (
(Select Distinct CustomerTypeId From Customers
),
map as (
select MainCountry, CustomerTypeId from cuntry,CustomerType 
)

select count(CustomerID) as CustomerCount,a.MainCountry,a.CustomerTypeID
from
map a left join Customers b on a.CustomerCount=b.CustomerCount and a.CustomerTypeID=b.CustomerTypeID