id name pro city 11 102型 广东 广州 13 102型 广东 深圳 16 103型 吉林 长春 25 102型 广东 广州 select top 100 * from tb where pro='广东' and city='广州' 想实现的功能是:要找出前100条所在地广州的记录,但是当广州这个记录不足100条时,则选择广东省下所有的前100,且广州的条目排在最前,请问高手应该如何写这个SQL谢谢。。
select top 100 * from( select * from tb where pro='广东' and city='广州' union select * from tb where pro='广东' ) as v
declare @sqlstr nvarchar(4000) SET @sqlstr= 'select top 100 * from tb' ... if(@Pro !=-1)--所在地省份 begin set @where=@where+' and Pro ='+@Province_w end if(@City !=-1)--所在地城市 begin set @where=@where+' and City ='+@City_w end ... EXEC sp_executesql @sqlstr我的存储过程是类似这样的,请问能在这个基础上改进吗。
--> --> (Roy)生成測試數據
declare @T table([id] int,[name] nvarchar(4),[pro] nvarchar(2),[city] nvarchar(2)) Insert @T select 11,N'102型',N'广东',N'广州' union all select 13,N'102型',N'广东',N'深圳' union all select 16,N'103型',N'吉林',N'长春' union all select 25,N'102型',N'广东',N'广州'
Select top 100 * from @T where pro='广东' order by case when city='广州' then 0 else 1 end 用order by +case when 就行了
select top 100 *,(case when city='广州' then 0 else 1 end) num from tb where pro like '%广东%' or city like '%广州%' order by num asc
我刚测试了下,like和UNION数据量大的时候区别还是蛮大的,你自己看到办吧
刚试了下,发现老大这个方法好强,非常受用。但是我有一个地方不是很明白 order by case when city='广州' then 0 else 1 end这句话的真实含义比如我试下 Select top 100 * from @T where pro='广东' order by 1 这样可以 Select top 100 * from @T where pro='广东' order by 0 这样就出错
select * from tb where pro='广东' and city='广州'
union
select * from tb where pro='广东' ) as v
declare @sqlstr nvarchar(4000) SET @sqlstr= 'select top 100 * from tb'
...
if(@Pro !=-1)--所在地省份
begin
set @where=@where+' and Pro ='+@Province_w
end
if(@City !=-1)--所在地城市
begin
set @where=@where+' and City ='+@City_w
end
...
EXEC sp_executesql @sqlstr我的存储过程是类似这样的,请问能在这个基础上改进吗。
declare @T table([id] int,[name] nvarchar(4),[pro] nvarchar(2),[city] nvarchar(2))
Insert @T
select 11,N'102型',N'广东',N'广州' union all
select 13,N'102型',N'广东',N'深圳' union all
select 16,N'103型',N'吉林',N'长春' union all
select 25,N'102型',N'广东',N'广州'
Select top 100 * from @T where pro='广东' order by case when city='广州' then 0 else 1 end
用order by +case when 就行了
order by case when city='广州' then 0 else 1 end这句话的真实含义比如我试下
Select top 100 * from @T where pro='广东' order by 1 这样可以
Select top 100 * from @T where pro='广东' order by 0 这样就出错