看起简单其实有点难的sql语句

dqj 2006-07-28 10:38:18
我通过
select grade,type_id ,count(type_id) b
from app
where type=4
GROUP BY type_id ,grade
得到如下记录:
grade type_id b
1 4 1
2 4 1
3 21 1
1 21 2
1 39 1

要求type_id 相同,如果b的数字大,只留下大的一行,就是 type_id 只能取一行不重的。如果b的数字相同,取grade 大的,即得到如下结果
grade type_id b

2 4 1
1 21 2
1 39 1

不知道我表达清楚没?









...全文
211 6 打赏 收藏 转发到动态 举报
写回复
用AI写文章
6 条回复
切换为时间正序
请发表友善的回复…
发表回复
selectplayer 2006-07-28
  • 打赏
  • 举报
回复
select y.*
(select distinct type_id from app) x
join
(select grade,type_id ,count(type_id) b
from app
where type=4
group by type_id ,grade
) y on y.type_id =x.type_id and y.b=(select top 1 b from
(select grade,type_id ,count(type_id) b
from app
where type=4
group by type_id ,grade
)z where z.type_id=y.type_id order by b desc)

这里面还是存在一个问题,LZ没说清除,就是存在type_id 和 b相同的情况,还是会有多条记录
昵称被占用了 2006-07-28
  • 打赏
  • 举报
回复
用临时表

select grade,type_id ,count(type_id) b
into #t
from app
where type=4
GROUP BY type_id ,grade

select * from #t a
where b=(select max(b) from #t where type_id=a.type_id)
and grade=(select max(grade) from #t where type_id=a.type_id and b=a.b)

drop table #t
zjcxc 2006-07-28
  • 打赏
  • 举报
回复
-- 2005
WITH temp
as(
select grade,type_id ,count(type_id) b
from app
where type=4
GROUP BY type_id ,grade
)
select * from temp a
where not exists(
select * from temp where type_id=a.type_id and(b>a.b or b=a.b and grade>a.grade))
fcuandy 2006-07-28
  • 打赏
  • 举报
回复
没加过滤条件 where type=4 ,有过滤条件请楼主自行加在 ON 的连接条件后面.
fcuandy 2006-07-28
  • 打赏
  • 举报
回复
SELECT MAX(a.grade),a.type_id,MAX(b.mb) b FROM
app a
INNER JOIN (SELECT type_id,MAX(b) mb FROM app GROUP BY type_id) b
ON a.type_id=b.type_id AND a.b=b.mb
GROUP BY a.type_id
LouisXIV 2006-07-28
  • 打赏
  • 举报
回复
--try?

select max(grade) grade,type_id,b
from
(
select grade,type_id,max(b) b
from(
select grade,type_id ,count(type_id) b
from app
where type=4
GROUP BY type_id ,grade
)t
group by grade,type_id
)t1
group by type_id,b

22,298

社区成员

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

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