首页 > 解决方案 > Power Bi:过滤包含字符串的 SQL Server 表

问题描述

我在 SQL Server 中有 2 个表:

包含国家名称的表 Country :

在此处输入图像描述

表协会名称和协会工作所在国家的名称:

在此处输入图像描述

在 Power Bi 中,我必须创建一个过滤器国家(美国、德国、法国、英国……)来过滤表社会:

例如,如果我在过滤器国家中输入“美国”,在我的矩阵中我将有社会 A 和社会 B。如果我在过滤器国家中输入“法国”,我将有社会 B 和社会 C。

(我的第一个想法是在 SQL Server 中添加一些二进制字段“IsInThisCountry”,然后使用这些字段作为过滤器)像这样: CASE WHEN country LIKE '%US%' THEN 1 ELSE 0 END 'IsUS'

但问题是如果我有 50 个国家,我将不得不创建 50 个过滤器

标签: sql-servertsqlfilterpowerbidax

解决方案


如果你有兼容 130 或更高版本的 SQL Server(使用 string_split),你可以在你的数据模型中尝试这样的事情来分割你的社团表中的分隔国家:

;with countries as (
select 'germany' as country
union all
select 'sweden'
),
socities as (
select 'A' as society, 'germany-sweden' as countries
union all
select 'B', 'sweden'
),
societyByCountry as (
select c.society, value as Country  from socities c
cross apply string_split(c.countries, '-') s
)

select c.country, s.society from countries c
inner join societyByCountry s on s.Country = c.country

推荐阅读