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

标签 sql sql-server

我有一个表“Customers”,其中包含 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,所以我想要一个默认值。

最佳答案

您应该将您的表与具有 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/

相关文章:

php - Mysql,如何在选择数据时自定义时间戳

sql - 我需要根据同一查询中其他字段的多个条件对一个字段的值求和。例如

mysql - 将日期时间除以日期

sql查询返回同一个表中没有重复记录的记录

wpf - 是否建议将 WCF 与 WPF 和 MVVM 一起使用从 SQL Server 检索数据?

php - 将多个条目插入多个表php pdo

sql-server - SQL Server 2008 类型转换案例

.net - 用于选择 SQL Server 和获取登录详细信息的通用对话框?

ios - iOS的同步框架提供程序

sql-server - 如何让 NHibernate 停止使用 nvarchar(4000) 来插入参数字符串?