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

就20分了,求一疑难sql文!大虾帮帮忙!
现在表A   中   有如下数据

    col1     col2
    002         1
    002         0
    004         0
    002         1
    003         1
    003         1
    002         1
    002         1
只有   col2   =   1   被查询出来,而且col1要把在一起的重复数据去掉,不在一起的不能去掉,
查询结果如下
  col1,   col2
    002         1
    003         1
    002         1

谢谢大家

------解决方案--------------------
select distinct col,col2 from tablename where col2 = 1
------解决方案--------------------
set nocount on
declare @a table(col1 varchar(10), col2 int)
insert @a select '002 ', 1
insert @a select '002 ', 0
insert @a select '004 ', 0
insert @a select '002 ', 1
insert @a select '003 ', 1
insert @a select '003 ', 1
insert @a select '002 ', 1
insert @a select '002 ', 1
insert @a select '003 ', 1


select identity(int,1,1) id, * into # from @a where col2 <> 0
select col1,col2 from # a where not exists(select * from # where id=a.id+1 and col1=a.col1 and col2=a.col2)
drop table #
------解决方案--------------------
create table a(col1 varchar(03),col2 int)
insert into a
select '002 ',1 union all
select '002 ',0 union all
select '004 ',0 union all
select '002 ',1 union all
select '003 ',1 union all
select '003 ',1 union all
select '003 ',0 union all
select '003 ',1 union all
select '002 ',1 union all
select '002 ',1 union all
select '002 ',1 union all
select '002 ',1 union all
select '003 ',1 union all
select '003 ',1 union all
select '004 ',1

select *,tem=0 into # from a where col2=1

declare @col1 varchar(03),@tem int
update #
set @tem=case when col1=@col1
then 1
else 0 end,
@col1=col1,
tem=@tem

select col1,col2 from # where tem=0
/*
col1 col2
---- -----------
002 1
003 1
002 1
003 1
004 1
*/

drop table a,#
------解决方案--------------------
这个结果集表没有主键?没有排序规则?

按照物理顺序?那最好的方法是在显示的时候处理,反正你显示的时候总是执行一个循环,只要把当前行的值和上一行对比下就知道要不要显示了。

写这种语句浪费数据库服务器的处理能力是不道德地。
------解决方案--------------------
declare @table table(id int,col1 varchar(10),col2 int)
insert into @table
select 1, '001 ',1
union all select 5, '001 ',1
union all select 6, '001 ',0
union all select 8, '002 ',1
union all select 10, '001 ',1
union all select 11, '002 ',1
union all select 13, '002 ',0
union all select 15, '003 ',1
union all select 16, '003 ',0
union all select 17, '003 ',1
union all select 20, '002 ',1
union all select 21, '001 ',1