请教多条件分组取唯一值

rmljoe 2010-06-04 12:44:48
tb
-----------------------
fA fB fC
----- ------ ------
AAA 1 1
AAA 2 2
BBB 1 1
BBB 3 3
CCC 1 1
CCC 2 1

当fA相同时,取fB最大的记录,可以这样写:
select * from tb a where not exists(select 1 from tb b where a.fA = b.fA and a.fB < b.fB)


现在表里新加了一条数据如下
CCC 2 2


当fA相同时,取fB最大的记录,当fA,fB都相同时,取fC最小的记录,SQL语句应该怎么写?
谢谢高手指点
...全文
185 7 打赏 收藏 转发到动态 举报
AI 作业
写回复
用AI写文章
7 条回复
切换为时间正序
请发表友善的回复…
发表回复
jwdream2008 2010-06-04
  • 打赏
  • 举报
回复
[Quote=引用 3 楼 rmljoe 的回复:]
引用 2 楼 jwdream2008 的回复:
SQL code
select * from tb a where not exists(select 1 from tb b where (a.fA = b.fA and a.fB<b.fB) OR (a.fA = b.fA And a.fb= b.fB And a.fC<b.fC)

谢谢,我测试一下,不过我要fC小的,是不是要把最后的小……
[/Quote]
你说的很对啊!你试一下!!
rmljoe 2010-06-04
  • 打赏
  • 举报
回复
[Quote=引用 2 楼 jwdream2008 的回复:]
SQL code
select * from tb a where not exists(select 1 from tb b where (a.fA = b.fA and a.fB<b.fB) OR (a.fA = b.fA And a.fb= b.fB And a.fC<b.fC)
[/Quote]
谢谢,我测试一下,不过我要fC小的,是不是要把最后的小于号改为大于号。
jwdream2008 2010-06-04
  • 打赏
  • 举报
回复
select * from tb a where not exists(select 1 from tb b where (a.fA = b.fA and a.fB<b.fB) OR (a.fA = b.fA  And a.fb= b.fB And a.fC<b.fC)

jwdream2008 2010-06-04
  • 打赏
  • 举报
回复
select * from tb a where not exists(select 1 from tb b where (a.fA = b.fA and a.fB) OR (a.fA = b.fA  And a.fb= b.fB And a.fC<b.fC)
--小F-- 2010-06-04
  • 打赏
  • 举报
回复
---少了个括号
--精减下代码
select
*
from
tb a
where
not exists(select 1 from tb b where a.fA = b.fA and (a.fB<b.fB OR a.fb= b.fB And a.fC>b.fC))
--小F-- 2010-06-04
  • 打赏
  • 举报
回复
--精减下代码
select
*
from
tb a
where
not exists(select 1 from tb b where a.fA = b.fA and (a.fB<b.fB OR a.fb= b.fB And a.fC>b.fC)
--小F-- 2010-06-04
  • 打赏
  • 举报
回复
[Quote=引用 3 楼 rmljoe 的回复:]
引用 2 楼 jwdream2008 的回复:
SQL code
select * from tb a where not exists(select 1 from tb b where (a.fA = b.fA and a.fB<b.fB) OR (a.fA = b.fA And a.fb= b.fB And a.fC<b.fC)

谢谢,我测试一下,不过我要fC小的,是不是要把最后的小……
[/Quote]

是的

22,301

社区成员

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

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