34,594
社区成员
发帖
与我相关
我的任务
分享
declare @T table([nid] int,[sid] int,[bank] int)
Insert @T
select 1,1,null union all
select 2,2,1 union all
select 3,2,3 union all
select 4,1,5 union all
select 5,3,null union all
select 6,1,2 union all
select 7,2,null
Select
*
from
@T t
where
[nid]=(select top 1 [nid] from @T where sid=t.sid order by case when [bank] is not null then 0 else 1 end asc,[nid] )
(7 個資料列受到影響)
nid sid bank
----------- ----------- -----------
2 2 1
4 1 5
5 3 NULL
(3 個資料列受到影響)
--修改:
create table tb (nid int , sid int, bank int)
insert into tb select 1,1,NULL
insert into tb select 2,2,1
insert into tb select 3,2,3
insert into tb select 4,1,5
insert into tb select 5,3,NULL
insert into tb select 6,1,2
insert into tb select 7,2,NULL
select * FROM TB A WHERE NID = (SELECT TOP 1 NID FROM TB WHERE sid =a.sid and bank is not null)
union
select * from tb a where nid = (select top 1 nid from tb where sid = a.sid )
and not exists(select 1 from tb where sid= a.sid and bank is not null)
drop table tb
set nocount on
create table tb (nid int , sid int, bank int)
insert into tb select 1,1,NULL
insert into tb select 2,2,1
insert into tb select 3,2,3
insert into tb select 4,1,5
insert into tb select 5,3,NULL
insert into tb select 6,1,2
insert into tb select 7,2,NULL
go
select * from tb a
where nid =(select top 1 nid from tb where sid = a.sid order by case when bank is null then 9999+sid else 9999 end,nid)
go
drop table tb
/*
nid sid bank
----------- ----------- -----------
2 2 1
4 1 5
5 3 NULL
*/
select * from tb t where bank is not null and not exists(select 1 from tb where sid=t.sid and bank<t.bank) order by sid
select * FROM TB A WHERE NID = (SELECT TOP 1 NID FROM TB WHERE sid =a.sid where bank is not null)
union
select * from tb a where nid = (select top 1 nid from tb where sid = a.sid order by sid)
and not exists(select 1 from tb where sid= a.sid and bank is not null)
create table tb (nid int , sid int, bank int)
insert into tb select 1,1,NULL
insert into tb select 2,2,1
insert into tb select 3,2,3
insert into tb select 4,1,5
insert into tb select 5,3,NULL
insert into tb select 6,1,2
insert into tb select 7,2,NULL
--不知是不是我的测试数据有问题.我感觉好像都有错.
select * from tb a where nid = (select top 1 nid from tb where sid=a.sid order by insull(bank,999999),sid)
-->生成测试数据
declare @tb table([nid] int,[sid] int,[bank] nvarchar(1))
Insert @tb
select 1,1,null union all
select 2,2,N'1' union all
select 3,2,N'3' union all
select 4,1,N'5' union all
select 5,3,N'0' union all
select 6,1,N'2' union all
select 7,2,N'0'
Select * from @tb t
where not exists (select 1 from @tb where [sid] =t.[sid] and [nid]<t.[nid] and bank is not null) and bank is not null
order by sid
/*
nid sid bank
----------- ----------- ----
4 1 5
2 2 1
5 3 0
*/