我有2个表,一个包含需要计数的列名列表,另一个包含要计算的数据
Table A
ProgramId ColumnName
1 Country
1 Gender
2 AgeRange
2 Region
Table B
ProgramId Country Gender AgeRange Region
1 USA M 18-25 Midwest
1 USA F <18 Northeast
1 MEX M <18 South
2 USA M 18-25 Midwest
2 USA M 26-35 Midwest
给定一个特定的ProgramId,我需要一个表A中每列的列表与表B中的每个值和计数相结合
需要输出示例(参数:@ProgramId = 1)
ColumnName ColumnValue ValueCount
Country USA 2
Country MEX 1
Gender M 2
Gender F 1
从我能够找到谷歌搜索,我需要某种动态陈述。这对我很好,因为只有访问表A的人才会是内部开发人员。
答案 0 :(得分:2)
MS SQL Server 2008架构设置:
CREATE TABLE TableA (ProgramId INT, ColumnName VARCHAR(20))
INSERT INTO TableA VALUES
(1 ,'Country'),
(1 ,'Gender'),
(2 ,'AgeRange'),
(2 ,'Region')
CREATE TABLE TableB (ProgramId VARCHAR(20), Country VARCHAR(20),
Gender VARCHAR(20), AgeRange VARCHAR(20), Region VARCHAR(20))
INSERT INTO TableB VALUES
('1' ,'USA' ,'M' ,'18-25' ,'Midwest'),
('1' ,'USA' ,'F' ,'<18' ,'Northeast'),
('1' ,'MEX' ,'M' ,'<18' ,'South'),
('2' ,'USA' ,'M' ,'18-25' ,'Midwest'),
('2' ,'USA' ,'M' ,'26-35' ,'Midwest')
查询1 :
;With x AS
(
Select *
From TableB
UNPIVOT(ColumnValue FOR ColumnName IN (Gender, Country))up
)
Select x.ColumnName
,x.ColumnValue
,COUNT(x.ColumnValue) ValueCount
From x
inner join TableA a ON x.ColumnName = a.ColumnName
WHERE x.ProgramId = 1 --<-- or maybe the parameter @ProgramId
GROUP BY x.ColumnName,x.ColumnValue
<强> Results 强>:
| ColumnName | ColumnValue | ValueCount |
|------------|-------------|------------|
| Country | MEX | 1 |
| Country | USA | 2 |
| Gender | F | 1 |
| Gender | M | 2 |
答案 1 :(得分:0)
第一步是生成代码。第二是运行它。
假设您的列没有特殊名称或奇怪的字符:
select @sql = ('select ' + cols +
', count(*) as ValueCount from b group by ' + cols
)
from (select stuff((select ', ' + a.ColumnName
from a
where programid = @programid
for xml path ('')
), 1, 2, ''
) as cols
) x;
exec sp_executesql @sql;