我正在尝试创建某种交叉表查询,以总结我们的人口统计种族数据如何存在。该表的结构包含5个种族列(种族1,种族2,种族3,种族4,种族5)。目的是显示有多少个人适合不同的群体,例如,某个在AS的任何领域中都有价值的人,他们还属于哪些其他(如果有)群体。
这是表格的基本结构
Person_ID Race1 Race2 Race3 Race4 Race5
815543 WH BA IN UN UN
815861 WH HP AS UN UN
823438 WH BA IN UN UN
825103 WH BA AS UN UN
825202 BA WH IN UN UN
825744 IN WH BA UN UN
这是预期最终结果的示例
AS BA HP IN UN WH
AS 1223 354 165 61 32216 1950
BA 823 112 264 731 119639 6135
HP 96 61 107 63 25510 285
IN 150 555 36 1000 63014 1510
UN 160 499 95 72 179927 3893
WH 2617 6012 477 1647 667126 125000
我想我应该首先取消数据显示,这样我每场比赛都有一个记录,但是我不确定下一步该怎么做。
答案 0 :(得分:0)
如果我对您的理解正确,那么当您有固定数量的比赛时,这是一个非常简单的计算。
此查询将返回您正在查找的内容:
declare @RACES TABLE (RACE varchar(16))
insert into @RACES (RACE) values ('AS'), ('BA'), ('HP'), ('IN'), ('UN'), ('WH')
select RACE,
(select count(*)
from MYTABLE
where RACE in (Race1, Race2, Race3, Race4, Race5) and
'AS' in (Race1, Race2, Race3, Race4, Race5)) as 'AS',
(select count(*)
from MYTABLE
where RACE in (Race1, Race2, Race3, Race4, Race5) and
'BA' in (Race1, Race2, Race3, Race4, Race5)) as 'BA',
(select count(*)
from MYTABLE
where RACE in (Race1, Race2, Race3, Race4, Race5) and
'HP' in (Race1, Race2, Race3, Race4, Race5)) as 'HP',
(select count(*)
from MYTABLE
where RACE in (Race1, Race2, Race3, Race4, Race5) and
'IN' in (Race1, Race2, Race3, Race4, Race5)) as 'IN',
(select count(*)
from MYTABLE
where RACE in (Race1, Race2, Race3, Race4, Race5) and
'UN' in (Race1, Race2, Race3, Race4, Race5)) as 'UN',
(select count(*)
from MYTABLE
where RACE in (Race1, Race2, Race3, Race4, Race5) and
'WH' in (Race1, Race2, Race3, Race4, Race5)) as 'WH'
from @RACES
尽管种族数可变,但是您将需要动态构建此SQL语句并使用sp_executesql启动它
https://www.mssqltips.com/sqlservertip/1160/execute-dynamic-sql-commands-in-sql-server/