Sql: Max(A),Max(B) GROUP BY id 但Max(B)是在Max(A)的前提下取的(如何实现)
如:
Id A B
-----------------
101 1 1
101 1 2
101 1 3
101 2 1
101 2 2
我想取
Id
101 2 3
先取 最大的A 在在最大的 A内取 最大的B 如何实现。。不会要写两个吧?
sql GROUP?BY?
------解决方案--------------------
----------------------------
-- Author :DBA_Huangzj(發糞塗牆)
-- Date :2013-01-18 16:25:20
-- Version:
-- Microsoft SQL Server 2008 R2 (SP1) - 10.50.2500.0 (X64)
-- Jun 17 2011 00:54:03
-- Copyright (c) Microsoft Corporation
-- Enterprise Edition (64-bit) on Windows NT 6.1 <X64> (Build 7601: Service Pack 1, v.721)
--
----------------------------
--> 测试数据:[huang]
if object_id('[huang]') is not null drop table [huang]
go
create table [huang]([Id] int,[A] int,[B] int)
insert [huang]
select 101,1,1 union all
select 101,1,2 union all
select 101,1,3 union all
select 101,2,1 union all
select 101,2,2
--------------开始查询--------------------------
SELECT id,a,MAX(b)b
FROM huang a
WHERE EXISTS (SELECT 1 FROM (
select id,MAX(a)a
from [huang]
GROUP BY id)b WHERE a.id=b.id AND a.a=b.a)
GROUP BY id,a
----------------结果----------------------------
/*
id a b
----------- ----------- -----------
101 2 2
(1 行受影响)
*/
------解决方案--------------------
select top 1 * from 表 order by a desc,b desc