求一条语句,该怎么解决
求一条语句
with temp as
(
select 'A3' a,1 b,100 c
union all
select 'A2' a,1 b,200 c
union all
select 'A1' a,1 b,300 c
union all
select 'B1' a,2 b,400 c
union all
select 'B2' a,2 b,400 c
union all
select 'B3' a,2 b,200 c
)
select * from temp
a b c
A3 1 100
A2 1 200
A1 1 300
B1 2 400
B2 2 400
B3 2 200
希望得到的结果是
A3 1 100
B1 2 400 或 B2 2 400
根据b字段进行分组,最C最大的一条记录,如果相同则任意取一条。
------解决思路----------------------
------解决思路----------------------
------解决思路----------------------
------解决思路----------------------
with temp as
(
select 'A3' a,1 b,100 c
union all
select 'A2' a,1 b,200 c
union all
select 'A1' a,1 b,300 c
union all
select 'B1' a,2 b,400 c
union all
select 'B2' a,2 b,400 c
union all
select 'B3' a,2 b,200 c
)
select * from temp
a b c
A3 1 100
A2 1 200
A1 1 300
B1 2 400
B2 2 400
B3 2 200
希望得到的结果是
A3 1 100
B1 2 400 或 B2 2 400
根据b字段进行分组,最C最大的一条记录,如果相同则任意取一条。
------解决思路----------------------
SELECT a,b,c FROM(
SELECT *
,ROW_NUMBER()OVER(PARTITION BY b ORDER BY c DESC)RN
FROM temp
)T
WHERE RN=1
------解决思路----------------------
with temp as
(
select 'A3' a,1 b,100 c
union all
select 'A2' a,1 b,200 c
union all
select 'A1' a,1 b,300 c
union all
select 'B1' a,2 b,400 c
union all
select 'B2' a,2 b,400 c
union all
select 'B3' a,2 b,200 c
)
,a1 AS
(
SELECT b,CASE WHEN b=1 THEN MIN(c) ELSE MAX(c) END c
FROM temp
GROUP BY b
)
SELECT b.*
FROM a1 a
CROSS APPLY
(
SELECT TOP 1 * FROM temp WHERE b=a.b AND c=a.c
) b
------解决思路----------------------
with temp as
(
select 'A3' a,1 b,100 c
union all
select 'A2' a,1 b,200 c
union all
select 'A1' a,1 b,300 c
union all
select 'B1' a,2 b,400 c
union all
select 'B2' a,2 b,400 c
union all
select 'B3' a,2 b,200 c
)
select a.a,a.b,a.c from
(select *,ROW_NUMBER()over(partition by b order by c desc) as id
from temp) as a where a.id=1
/*
a b c
-------------
A1 1 300
B2 2 400
-------------
*/
------解决思路----------------------
Select *
From
(
Select Row_Number() Over (partition By b Order By c Desc) Row, *
From temp
) T
Where Row=1