34,587
社区成员
发帖
与我相关
我的任务
分享
select top 10 m.id as id, rtrim(left(title,11)) as titles,Clicks,AddTime,Auther,meno,Classes,s.phone as phone,s.name as name from
(select t.* from tb t where refreshtime = (select max(OrderCol) from tb where userid = t.userid) ) m
inner join UserTable on s.userid=m.userid where m.id = (select max(id) from
(select t.* from tb t where OrderCol = (select max(OrderCol) from tb where isshow=0 and userid = t.userid)) n
where m.userid = n.userid)
order by OrderColdesc
[code=SQL]declare @t table(type varchar(4),detail varchar(10))
insert @t select
'001','a' union select
'001','sss' union select
'001','gssfa' union select
'002','fdsf' union select
'002','fs' union select
'002','gahas' union select
'003','sdga' union select
'003','hahasg' union select
'003','gdsag'
select a.type,a.detail
from @t a
join @t b
on a.type= b.type
group by a.type,a.detail
having count(case when a.detail <= b.detail then 1 else null end) < = 2 --可动态修改
order by a.type asc
/*
type detail
---- ----------
001 gssfa
001 sss
002 fs
002 gahas
003 hahasg
003 sdga
(所影响的行数为 6 行)
*/
select a.* from @t a
where exists (select count(*)
from @t
where type = a.type and detail > a.detail having Count(*) < 2)
order by a.type
/*
type detail
---- ----------
001 gssfa
001 sss
002 fs
002 gahas
003 hahasg
003 sdga
(所影响的行数为 6 行)
*/
select a.* from @t a
where exists (select count(*)
from @t
where type = a.type and detail < a.detail having Count(*) < 2)
order by a.type
/*
type detail
---- ----------
001 a
001 gssfa
002 fdsf
002 fs
003 gdsag
003 hahasg
(所影响的行数为 6 行)
*/
select a.*
from @t a
where detail in (select top 2 detail
from @t where type=a.type
order by detail desc)
order by a.type,a.detail
/*
type detail
---- ----------
001 gssfa
001 sss
002 fs
002 gahas
003 hahasg
003 sdga
(所影响的行数为 6 行)
*/
select a.*
from @t a
where detail in (select top 2 detail
from @t where type=a.type
order by detail asc)
order by a.type,a.detail
/*
type detail
---- ----------
001 a
001 gssfa
002 fdsf
002 fs
003 gdsag
003 hahasg
(所影响的行数为 6 行)
*/
[/code]--取小
select top 10 m.* from
(
select t.* from tb t where OrderCol = (select min(OrderCol) from tb where 分类 = t.分类)
) m where id = (select min(id) from
(
select t.* from tb t where OrderCol = (select min(OrderCol) from tb where 分类 = t.分类)
) n where m.分类 = n.分类
)
--取大
select top 10 m.* from
(
select t.* from tb t where OrderCol = (select max(OrderCol) from tb where 分类 = t.分类)
) m where id = (select max(id) from
(
select t.* from tb t where OrderCol = (select max(OrderCol) from tb where 分类 = t.分类)
) n where m.分类 = n.分类
)
select * from 文章表 a
where not exists(select 1 from 文章表 where 类别=a.类别 and OrderCol>a.OrderCol)
order by OrderCol desc