首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 数据库 > SQL Server >

就20分了,求一疑难sql文!帮帮忙

2012-01-24 
就20分了,求一疑难sql文!大虾帮帮忙!现在表A中有如下数据col1col200210020004000210031003100210021只有co

就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



select id,col1,col2
from @table a
where not exists(select 1 from @table
where id in(select max(id)as id from @table where id <a.id and col2=1)
and col1=a.col1 and col2=a.col2)and col2=1

/*结果
id col1 col2
----------- ---------- -----------
1 001 1
8 002 1
10 001 1
11 002 1
15 003 1
20 002 1
21 001 1
*/

热点排行
Bad Request.