SQL数据库表名为PP,表结构如下:
编码 数值
1 0.2
2 0.1
3 0.5
4 1.1
1 0.5
2 0.8
3 2.5
4 0.1
1 8
2 1.1
3 5
4 6.0
. .
. .
. .
如何用select语句查询后结果是:
编码 总和 数值1 数值2 数值3 ...
1 8.7 0.2 0.5 8 ...
2 2.0 0.1 0.8 1.1 ...
3 8 0.5 2.5 5 ...
4 7.2 1.1 0.1 6 ...
编码 数值
1 0.2
2 0.1
3 0.5
4 1.1
1 0.5
2 0.8
3 2.5
4 0.1
1 8
2 1.1
3 5
4 6.0
. .
. .
. .
如何用select语句查询后结果是:
编码 总和 数值1 数值2 数值3 ...
1 8.7 0.2 0.5 8 ...
2 2.0 0.1 0.8 1.1 ...
3 8 0.5 2.5 5 ...
4 7.2 1.1 0.1 6 ...
declare @PP table (编码 int,数值 numeric(2,1))
insert into @PP
select 1,0.2 union all
select 2,0.1 union all
select 3,0.5 union all
select 4,1.1 union all
select 1,0.5 union all
select 2,0.8 union all
select 3,2.5 union all
select 4,0.1 union all
select 1,8 union all
select 2,1.1 union all
select 3,5 union all
select 4,6.0;with maco as
(
select row_number() over (partition by 编码 order by (select 1)) as rid, * from @PP
)select 编码,总和=sum(数值),
max(case rid when 1 then 数值 else null end) as 数值1,
max(case rid when 2 then 数值 else null end) as 数值2,
max(case rid when 3 then 数值 else null end) as 数值3
from maco
group by 编码
/*
编码 总和 数值1 数值2 数值3
------ ------- ---------- -------------- ----------------
1 8.7 0.2 0.5 8.0
2 2.0 1.1 0.8 0.1
3 8.0 0.5 2.5 5.0
4 7.2 6.0 0.1 1.1
*/
set @sql = 'select 编码 '
select @sql = @sql + ' sum(数值) as 数值, sum(case 编码 when ''' + ltrim(编码) + ''' then 数值 else 0.0 end) [' 数值+ ltrim(编码) + ']'
from (select distinct 编码 from tb) as a
set @sql = @sql + ' from tb group by 编码'
exec(@sql)
'编码',
SUM('数值') As '总和',
SUM(Case '编码' When 1 Then '数值' Else 0 End ) As '数值1',
SUM(Case '编码' When 2 Then '数值' Else 0 End ) As '数值2',
....
From PP
Group by '编码'
select row_number() over (partition by 编码 order by (select 1)) as rid, * from @PP喜欢这段
select 1 from @PP
SUM(Case '编码' When 2 Then '数值' Else 0 End ) As '数值2',
...."这几句可以简单吗?
就是要把同一个编码的数据,放在同一行