select 編號,max(isnull(描述,''),sum(isnull(數量,0)),max(isnull(單位,'')) from 表 group by 編號
select 编号,描述,sum(数量),单位 from 表 group by 编号,描述,单位
你的要求不合理,如果 10 a10 1 pc 10 Null 1 kg 那应该用那个单位呢?先给出一个 select 编号,数量=sum(数量),单位=max(单位) from 表 group by 编号
TO:meilian01(meilian) 谢谢。 您的结果集如下:这不是我的要求。 编号 描述 数量 单位 10 a10 Null Null 10 a10 1 pc 10 Null 1 pc 20 a20 5 set 30 a30 1 kg
TO:daijingjie2002(艰苦创业) 单位要么没有要么肯定一样。
selct a.编号, b.描述, a.数量, c.单位 from (select 编号,sum(数量) as 数量 from 表 group by 编号) a, (select distinct 编号,描述 from 表 where 描述 is not null) b, (select distinct 编号,单位 from 表 where 单位 is not null) c where a.编号 = b.编号 and a.编号 = c.编号
create table tb(编号 int,描述 varchar(10), 数量 int, 单位 varchar(10)) insert into tb select 10,'a10',Null, Null union select 10,'a10',1,'pc' union select 10,Null,1,'pc' union select 20,'a20',3,'set' union select 20,'a20',2,'set' union select 30,'a30',1,'kg'select 编号,描述 = max(描述),数量=sum(数量),单位=max(单位) from tb group by 编号drop table tb /*结果 10 a10 2 pc 20 a20 5 set 30 a30 1 kg */
select 编号,max(描述),sum(isnull(数量,0)),max(单位) from [表] group by 编号
10 a10 1 pc
10 Null 1 kg
那应该用那个单位呢?先给出一个
select 编号,数量=sum(数量),单位=max(单位) from 表 group by 编号
您的结果集如下:这不是我的要求。
编号 描述 数量 单位
10 a10 Null Null
10 a10 1 pc
10 Null 1 pc
20 a20 5 set
30 a30 1 kg
单位要么没有要么肯定一样。
selct a.编号,
b.描述,
a.数量,
c.单位
from
(select 编号,sum(数量) as 数量 from 表 group by 编号) a,
(select distinct 编号,描述 from 表 where 描述 is not null) b,
(select distinct 编号,单位 from 表 where 单位 is not null) c
where
a.编号 = b.编号 and a.编号 = c.编号
insert into tb
select 10,'a10',Null, Null
union
select 10,'a10',1,'pc'
union
select 10,Null,1,'pc'
union
select 20,'a20',3,'set'
union
select 20,'a20',2,'set'
union
select 30,'a30',1,'kg'select 编号,描述 = max(描述),数量=sum(数量),单位=max(单位) from tb group by 编号drop table tb
/*结果
10 a10 2 pc
20 a20 5 set
30 a30 1 kg
*/
select 编号,max(描述),sum(isnull(数量,0)),max(单位)
from [表] group by 编号