问一句sql的写法

xiaotupansy 2011-07-12 10:19:56
IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[test]') AND type in (N'U'))
DROP TABLE [dbo].test
create table test(cid int,addr nvarchar(100) null,isdefault int null)
insert into test select 1,'aaa',null
union select 1,'bbb',1
union select 2,'ccc',1
union select 2,'ddd',1
union select 2,'eee',0
union select 2,'fff',1

select * from test

逻辑是,如果isdefault为1,那么优先取1的记录
如果不为1,那么取0,最后取null

对每个id,只有取1条记录就可以了,希望结果如下

1 'bbb' 1
2 'ccc' 1/这里也可以是2 'ddd' 1, 2 'fff' 1,次序随意
...全文
79 2 打赏 收藏 转发到动态 举报
写回复
用AI写文章
2 条回复
切换为时间正序
请发表友善的回复…
发表回复
Zoezs 2011-07-12
  • 打赏
  • 举报
回复
select * from test where isdefault=1
union all
select * from test where isdefault=0
union all
select * from test where isdefault is null
order by cid
AcHerat 2011-07-12
  • 打赏
  • 举报
回复

create table test(cid int,addr nvarchar(100) null,isdefault int null)
insert into test select 1,'aaa',null
union select 1,'bbb',1
union select 2,'ccc',1
union select 2,'ddd',1
union select 2,'eee',0
union select 2,'fff',1
go

;with AcHerat as
(
select *,rid=row_number() over (partition by cid order by (case when isdefault = 1 then 0
when isdefault = 0 then 1 else 2 end))
from test
)

select *
from AcHerat
where rid = 1

drop table test


/****************

cid addr isdefault rid
----------- ---------------------------------------------------------------------------------------------------- ----------- --------------------
1 bbb 1 1
2 fff 1 1

(2 行受影响)

22,209

社区成员

发帖
与我相关
我的任务
社区描述
MS-SQL Server 疑难问题
社区管理员
  • 疑难问题社区
  • 尘觉
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧