日期:2014-05-17  浏览次数:20437 次

SQL 怎样将重复记录字段加总,然后再删除其中一条,见描述,在线等
有表A:
A01     A02     A03(int)
-------------------
M0001   n01     10
M0002   n01     5
M0003   n02     2
M0004   n02     4
.....

想得到如下效果:
A01     A02     A03(int)
-------------------
M0001   n01     15 
M0003   n02     6 
.....

加总后只保留A01最小的这条记录
------解决方案--------------------
更正一下
----------------------------------------------------------------
-- Author  :DBA_Huangzj(發糞塗牆)
-- Date    :2014-02-19 17:03:52
-- Version:
--      Microsoft SQL Server 2012 (SP1) - 11.0.3128.0 (X64) 
-- Dec 28 2012 20:23:12 
-- Copyright (c) Microsoft Corporation
-- Enterprise Edition (64-bit) on Windows NT 6.2 <X64> (Build 9200: )
--
----------------------------------------------------------------
--> 测试数据:[a]
if object_id('[a]') is not null drop table [a]
go 
create table [a]([A01] varchar(5),[A02] varchar(3),[A03] int)
insert [a]
select 'M0001','n01',10 union all
select 'M0002','n01',5 union all
select 'M0003','n02',2 union all
select 'M0004','n02',4
--------------开始查询--------------------------

select MIN([A01])[a01],[A02],SUM([A03])[A03]
from [a]
GROUP BY [A02]
----------------结果----------------------------
/* 
a01   A02  A03
----- ---- -----------
M0001 n01  15
M0003 n02  6


*/

------解决方案--------------------
是这样吗:

--drop table A

create table A(A01 varchar(10), A02 varchar(10), A03 int)


insert into A
select 'M0001',   'n01',     10 union all
select 'M0002',   'n01',     5 union all
select 'M0003',   'n02',     2 union all
select 'M0004',   'n02',     4
go

select min(A01) a01, A02,SUM(A03) a03
from A
group by A02
/*
a01 A02 a03
M0001 n01 15
M0003 n02 6
*/

------解决方案--------------------

if object_id('t100') is  not null drop table t100

create table t100(a01 varchar(30),a02 varchar(20),a03 int)


insert t100 values('M0001','n01',10)
insert t100 values('M0002','n01',5)
insert t100 values('M0003','n02',2)
insert t100 values('M0004','n02',4)


select [a01]=min(a01),a02,[a03]=sum(a03) from t100 group by a02