The maximum value of the SQL data group, the first one, and the first three methods are summarized. All three instances are simple operations based on the data from GROUPBY. For more information, see.
The maximum number of SQL data groups, the first one, and the first three methods are summarized. All three instances are simple operations based on the GROUP BY data. For more information, see.
Retrieve the first three records of a group
| The Code is as follows: |
|
|
SELECT Course,
SUM (bonus) AS bonus
FROM (SELECT course,
Student ID,
Score
FROM exam AS
WHERE (select count (*)
FROM exam
WHERE course = a. Course
AND student ID <> a. Student ID
AND score> a. Score
) <3
) AS B
Group by course |
Obtain the first record of the Group
Example
The Demo data in the table is of the string type, and records sorted by Time (also a string) in order are as follows:
Num Name Time
1 a 2009/05/01
1 a 2009/05/02
1 a 2009/05/03
2 B 2009/05/04
2 B 2009/05/05
3 c 2009/05/06
3 c 2009/05/07
5 e 2009/05/08
1 a 2009/05/09
1 a 2009/05/10
I want to output the first data record similar to the one in each group grouped by Num. For example, I want to obtain the following record after the above record operation:
Num Name Time
1 a 2009/05/01
2 B 2009/05/04
3 c 2009/05/06
5 e 2009/05/08
1 a 2009/05/09
SQL code
| The Code is as follows: |
|
|
Declare @ Tab table
(Num int, Name varchar (2), Time DATETIME)
Insert into @ tab select 1, 'A', '2017/01'
Insert into @ tab select 1, 'A', '2017/02'
Insert into @ tab select 1, 'A', '2017/03'
Insert into @ tab select 2, 'B', '2017/04'
Insert into @ tab select 2, 'B', '2017/05'
Insert into @ tab select 3, 'C', '2017/06'
Insert into @ tab select 3, 'C', '2017/07'
Insert into @ tab select 5, 'E', '2017/08'
Insert into @ tab select 1, 'A', '2017/09'
Insert into @ tab select 1, 'A', '2017/10'
Select * from @ Tab t where not exists (select 1 from @ Tab where num = t. num and [time] < p><>
/*
Num Name Time
--------------------------------------
1 a 00:00:00. 000
2 B 00:00:00. 000
3 c 00:00:00. 000
5 e 00:00:00. 000
(Four rows affected)
*/ |
Maximum group records
Example: test Table a B c
1 5 abc
2 6 bcd
1 7 ade
2 8 adc
If the records of all columns with the maximum value of Column B are grouped by column:
Result a B c
1 6 bcd
2 8 adc
You can use the following statement:
| The Code is as follows: |
|
Select * from test where B in (select max (id) from test group by)
Applicable to All databases:
Select t1.a, t1. B, t1.c
From test t1
Inner join
(Seelct a, max (B) as B from test group by a) t2
On t1.a = t2.a and t1. B = t2. B
Applicable to All databases:
Select a, B, c
From (
Select a, B, c
, Row_number () over (partition by a order by B desc) rn
From test
)
Where rn = 1 |