简体   繁体   中英

get min max values in group of data

In sql server i have a table having more than crores of records like

empnos  date
a1  18-Jul-13
a1  18-Jul-13
a1  18-Jul-13
a1  18-Jul-13
a2  18-Jul-13
a2  18-Jul-13
a2  18-Jul-13
a3  18-Jul-13
a1  19-Jul-13
a2  19-Jul-13
a3  19-Jul-13
a1  20-Jul-13
a2  20-Jul-13
a3  20-Jul-13

now i want output where it is grouped and each group has min max value so output should be like 1 below

EMPNO   DATE
A1  18-Jul-13
A1  20-Jul-13
A2  18-Jul-13
A2  20-Jul-13
A3  18-Jul-13
A3  20-Jul-13

Now there are some changes in requirement i want is in same table i want is top two max values

If you're using SQL-Server you can use ROW_NUMBER or DENSE_RANK :

WITH CTE AS(
   SELECT empnos,  
          date,
          rn = row_number() over (partition by empnos order by date desc)
   FROM dbo.TableName
)
SELECT * FROM CTE WHERE RN <= 2

Demo

If you also want the Min-/Max values per empnos , you can use the OVER clause:

WITH CTE AS(
   SELECT empnos,  
          date,
          min = Min(date) over (partition by empnos),
          max = Max(date) over (partition by empnos),
          rn = row_number() over (partition by empnos order by date desc)
   FROM dbo.TableName
)
SELECT * FROM CTE WHERE RN <= 2

Demo

Select empnos ,  Max(date) from TableName Group by empnos 
Union
Select empnos ,  Min(date) from TableName Group by empnos order by empnos 

Sql Fiddle Demo

 select * from (
    Select empnos ,  Max(date) dat from TableName Group by empnos 
    Union all
    Select empnos ,  Min(date) dat from TableName Group by empnos 
 ) a 
    order by empnos, dat

union all or union can be used based on your requirement

DECLARE @t table (
   empnos   char(2)
 , the_date date
);

INSERT INTO @t (empnos, the_date)
  VALUES ('a1', '18-Jul-13')
       , ('a1', '18-Jul-13')
       , ('a1', '18-Jul-13')
       , ('a1', '18-Jul-13')
       , ('a2', '18-Jul-13')
       , ('a2', '18-Jul-13')
       , ('a2', '18-Jul-13')
       , ('a3', '18-Jul-13')
       , ('a1', '19-Jul-13')
       , ('a2', '19-Jul-13')
       , ('a3', '19-Jul-13')
       , ('a1', '20-Jul-13')
       , ('a2', '20-Jul-13')
       , ('a3', '20-Jul-13');

SELECT empnos
     , Max(the_date) As the_date
FROM   @t
GROUP
    BY empnos

UNION ALL

SELECT empnos
     , Min(the_date) As the_date
FROM   @t
GROUP
    BY empnos

ORDER
    BY empnos
     , the_date

Result:

empnos the_date
------ ----------
a1     2013-07-18
a1     2013-07-20
a2     2013-07-18
a2     2013-07-20
a3     2013-07-18
a3     2013-07-20

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM