问题
I want to get the first row for every GV(TeacherID)
GV | Class| SUM
GV1| L001 | 5000
GV1| L002 | 5000
GV1| L003 | 5000
GV2| L002 | 7000
GV2| L003 | 7000
GV2| L001 | 7000
GV3| L001 | 8000
GV3| L002 | 8000
GV3| L003 | 8000
Help me.
回答1:
Edit: ok, now you've edited the question such that this answer looks completely irrelevant...sigh...I'll leave it in case it helps you get started. Cheers.
The simplest solution given your specs:
select teacherid
from mytable
group by teacherid;
If you need other information in addition to the teacherid
:
select teacherid, ...other cols...
from (select teacherid, ...other cols...
row_number() over (
partition by teacherid
order by classid /* or class as per edit */) as row_num
from mytable) my_derived_table
where my_derived_table.row_num = 1;
Caveat emptor: I don't have an installation of SQL-Server handy to test on, so syntax may not be exactly correct; but it's close.
回答2:
WITH T AS (
SELECT yourTable.*, ROW_NUMBER() OVER(PARTITION BY TeacherID
ORDER BY ClassID) AS RN
FROM yourTable
)
SELECT *
FROM T
WHERE RN = 1
回答3:
DDL
create table #t
(
GV varchar(4),
Class varchar(4),
[SUM] int
)
Sample Records
insert into #t(GV, Class, [SUM])values('GV1', 'L001', 5000)
insert into #t(GV, Class, [SUM])values('GV1', 'L002', 5000)
insert into #t(GV, Class, [SUM])values('GV1', 'L003', 5000)
insert into #t(GV, Class, [SUM])values('GV2', 'L002', 7000)
insert into #t(GV, Class, [SUM])values('GV2', 'L003', 7000)
insert into #t(GV, Class, [SUM])values('GV2', 'L001', 7000)
insert into #t(GV, Class, [SUM])values('GV3', 'L001', 8000)
insert into #t(GV, Class, [SUM])values('GV3', 'L002', 8000)
insert into #t(GV, Class, [SUM])values('GV3', 'L003', 8000)
Query
Select GV, class, [sum] from
(
Select Row_Number() Over(Partition by GV Order by GV ) as RowId, * from #t
)K
Where RowId = 1
drop table #t
Resultset
GV class sum
---- ----- ----
GV1 L001 5000
GV2 L002 7000
GV3 L001 8000
来源:https://stackoverflow.com/questions/9287119/get-first-row-for-one-group