读书人

应该不会难倒前辈的查询语句解决思路

发布时间: 2012-03-26 15:46:56 作者: rapoo

应该不会难倒前辈的查询语句
有一个表

单据号 行号 科目号
01 1 A
01 2 B
02 1 A
02 2 C
02 3 D
03 1 C
04 1 B
04 2 E

需要输出科目号有A或者B的单据(只要有一行有A或者B,单据的所有行就全部输出)
输出
单据号 行号 科目号
01 1 A
01 2 B
02 1 A
02 2 C
02 3 D
04 1 B
04 2 E

还请各位赐教!

[解决办法]

SQL code
select *from tb twhere exists(select 1 from tb where 单据号=t.单据号 and (科目号='A' or 科目号='B'))
[解决办法]
SQL code
declare @T table (单据号 varchar(2),行号 int,科目号 varchar(1))insert into @Tselect '01',1,'A' union allselect '01',2,'B' union allselect '02',1,'A' union allselect '02',2,'C' union allselect '02',3,'D' union allselect '03',1,'C' union allselect '04',1,'B' union allselect '04',2,'E'select distinct a.* from @t a left join @t b on a.单据号=b.单据号 where b.科目号='a' or b.科目号='b'/*单据号  行号          科目号---- ----------- ----01   1           A01   2           B02   1           A02   2           C02   3           D04   1           B04   2           E*/
[解决办法]
探讨
SQL code

declare @T table (单据号 varchar(2),行号 int,科目号 varchar(1))
insert into @T
select '01',1,'A' union all
select '01',2,'B' union all
select '02',1,'A' union all
select '02',2,'C' union all
……

[解决办法]
SQL code
create table tb(    单据号    int,    行号    int,    科目号    nvarchar(1))insert into tb values(01,1,'A')insert into tb values(01,1,'B')insert into tb values(02,1,'A')insert into tb values(02,1,'C')insert into tb values(02,1,'D')insert into tb values(03,1,'C')insert into tb values(04,1,'B')insert into tb values(04,1,'E')select * from tb where 单据号 in(select 单据号 from tb where 科目号 in('A','B') group by 单据号)/*单据号,行号,科目号1,1,A1,1,B2,1,A2,1,C2,1,D4,1,B4,1,E(7 行受影响) 

读书人网 >SQL Server

热点推荐