日期:2014-05-18  浏览次数:20446 次

重复记录并和
表 A
姓名 衣服 裤子 鞋 金额
a 1 11
a 1 89
a 1 67

表 B
姓名 衣服 裤子 鞋 总金额
a 11 89 67 167



请教,怎么用SQL 语句吧表A转换成表B啊?????




------解决方案--------------------
探讨

表 A
姓名 衣服 裤子 鞋 金额
a 1 null null 11
a null 1 null 89
a null null 1 67

表 B
姓名 衣服 裤子 鞋 总金额
a 11 89 67 167


是这样的。格式没调好。请见谅

------解决方案--------------------
SQL code
create table 表A(姓名 varchar(10),衣服 INT,裤子 INT,鞋 INT,金额 INT)
insert into 表A select 'a',1,null,null,11
insert into 表A select 'a',null,1,null,89
insert into 表A select 'a',null,null,1,67
go
select 姓名,
sum(case when 衣服 is not null then 金额 else 0 end)as 衣服,
sum(case when 裤子 is not null then 金额 else 0 end)as 裤子,
sum(case when 鞋 is not null then 金额 else 0 end)as 鞋,
sum(金额)as 总金额
from 表A
group by 姓名
/*
姓名         衣服          裤子          鞋           总金额
---------- ----------- ----------- ----------- -----------
a          11          89          67          167

(1 行受影响)

*/
go
drop table 表A