读书人

怎么剔除相同记录统计记录数

发布时间: 2012-06-10 14:03:15 作者: rapoo

如何剔除相同记录统计记录数
我有一表mc
id ch
1 wwk-222
2 wwk-222
3 wwk-086
4 wwk-076
5 wwk-089
6 wwk-079

CREATE procedure dwchts
@ch varchar(10)
as
begin
if len(@ch)=1
exec('select count(ch) as ts from mc where SUBSTRING(ch,7,1)='+''''+@ch+'''')
if len(@ch)=2
exec('select count(ch) as ts from mc where SUBSTRING(ch,6,2)='+''''+@ch+'''')
if len(@ch)=3
exec('select count(ch) as ts from mc where SUBSTRING(ch,5,3)='+''''+@ch+'''')
end
GO
执行存储过程是统计6条
我想得到ch完全相同的作1条,应该是5条,如何写

[解决办法]
select count(distinct ch) as ts from mc where。。。。
[解决办法]

SQL code
--> 测试数据:[test]if object_id('[test]') is not null drop table [test]create table [test]([id] int,[ch] varchar(7))insert [test]select 1,'wwk-222' union allselect 2,'wwk-222' union allselect 3,'wwk-086' union allselect 4,'wwk-076' union allselect 5,'wwk-089' union allselect 6,'wwk-079'select COUNT(distinct [ch]) as [ch] from test/*ch------5*/--去掉重复使用distinct
[解决办法]
SQL code
--> 测试数据:[test]if object_id('[test]') is not null drop table [test]create table [test]([id] int,[ch] varchar(7))insert [test]select 1,'wwk-222' union allselect 2,'wwk-222' union allselect 3,'wwk-086' union allselect 4,'wwk-076' union allselect 5,'wwk-089' union allselect 6,'wwk-079'select * from test awhere a.id=(select MIN(b.id) from test b where a.ch=b.ch)order by id --相同的ch取最大id的时候把min改成max/*id    ch-------------------1    wwk-2223    wwk-0864    wwk-0765    wwk-0896    wwk-079*/ 

读书人网 >SQL Server

热点推荐