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

在线求一SQL语句,关于分组的问题
假如有一张表,字段为,编号,序号,数量  
内容为: 001,1,1  
  001,2,2  
  001,3,3  
  001,4,4  
  001,5,5 
  002,1,1  
  002,2,2  
  002,3,3  
  002,4,4  
  002,5,5 
怎么样将这个表中的内容分为两部分,一部分是编号不同的前两项,一部分是剩余的项,即一个查询出来的表是
001,1,1  
001,2,2 
002,1,1  
002,2,2 
剩余的是一个查询中的内容

------解决方案--------------------
SQL code
create table tb(
id char(3),
a int,
b int)

insert tb select  '001',1,1
insert tb select  '001',2,2   
insert tb select  '001',3,3   
insert tb select  '001',4,4   
insert tb select  '001',5,5 
insert tb select  '002',1,1   
insert tb select  '002',2,2   
insert tb select  '002',4,4   
insert tb select  '002',5,5 

select a.id,a.a,a.b
from tb a,tb b
where a.id=b.id
group by a.id,a.a,a.b
having count(case when a.a>=b.a and a.b>=b.b then 1 else null end)<=2

drop table tb

/*
id   a           b           
---- ----------- ----------- 
001  1           1
001  2           2
002  1           1
002  2           2

(所影响的行数为 4 行)
*/

------解决方案--------------------
SQL code

create table tb(编号 varchar(10),序号 int,数量 int)
insert into tb values('001',1,1)       
insert into tb values('001',2,2)       
insert into tb values('001',3,3)       
insert into tb values('001',4,4)       
insert into tb values('001',5,5)   
insert into tb values('002',1,1)       
insert into tb values('002',2,2)       
insert into tb values('002',3,3)       
insert into tb values('002',4,4)       
insert into tb values('002',5,5)
go

select id=identity(int,1,1),* into # from tb

select  编号 ,序号 , 数量   
from # a
where (select count(1) from # where a.编号=编号 and id<a.id)<2

/*
编号         序号          数量          
---------- ----------- ----------- 
001        1           1
001        2           2
002        1           1
002        2           2

(4 row(s) affected)
*/

------解决方案--------------------
SQL code
--1
create table tb(编号 varchar(10),序号 int,数量 int)
insert into tb values('001bl