对不起,我没有提出问题的好标题,所以请随意更改。
我可以用MS SQL server 2012中的一个最小例子描述我的问题:
create table #tmp
(
RowID varchar(10),
SectionCode int,
SectionName varchar(10)
)
insert into #tmp values('Record1' , 1 , 'AB');
insert into #tmp values('Record1' , 2 , 'CD');
insert into #tmp values('Record1' , 3 , 'EF');
insert into #tmp values('Record2' , 1 , 'AB');
insert into #tmp values('Record2' , 4 , 'GH');
insert into #tmp values('Record2' , 5 , 'IJ');
insert into #tmp values('Record3' , 2 , 'CD');
insert into #tmp values('Record3' , 5 , 'IJ');
我正在尝试为每个记录结果创建一行,其中每个部分都是一列,如果有一个与部分关联的行,则相应的列值会增加。这是(不)我想要的(不同行上的相同记录数据)
select RowID,
case when SectionName = 'AB' then 1 else 0 end as [AB Section] ,
case when SectionName = 'CD' then 1 else 0 end as [CD Section] ,
case when SectionName = 'EF' then 1 else 0 end as [EF Section] ,
case when SectionName = 'GH' then 1 else 0 end as [GH Section] ,
case when SectionName = 'IJ' then 1 else 0 end as [IJ Section]
from #tmp
group by RowID , SectionName
给出了这个输出:
我需要这个:
提前致谢
答案 0 :(得分:2)
您可以使用pivot来实现此目的,并根据需要操作各个部分的值。
SELECT rowid
,CASE
WHEN ab IS NULL
THEN 0
ELSE 1
END AS ab
,CASE
WHEN cd IS NULL
THEN 0
ELSE 1
END AS cd
,CASE
WHEN ef IS NULL
THEN 0
ELSE 1
END AS ef
,CASE
WHEN gh IS NULL
THEN 0
ELSE 1
END AS gh
,CASE
WHEN ij IS NULL
THEN 0
ELSE 1
END AS ij
FROM (
SELECT *
FROM #tmp
PIVOT(MAX(Sectioncode) FOR Sectionname IN (
AB
,CD
,EF
,GH
,IJ
)) pvt
) tab
我认为您显示的结果对于记录ID 2不正确。记录ID 2的ij应为1.
答案 1 :(得分:1)
我想你想要这个:
select RowID,
sum(case when SectionName = 'AB' then 1 else 0 end) as [AB Section] ,
sum(case when SectionName = 'CD' then 1 else 0 end) as [CD Section] ,
sum(case when SectionName = 'EF' then 1 else 0 end) as [EF Section] ,
sum(case when SectionName = 'GH' then 1 else 0 end) as [GH Section] ,
from #tmp
group by RowID;
也就是说,您需要聚合功能。 group by
应包含您要定义每一行的列(即只有RowId
)。