获取数据组中的最小最大值

时间:2013-07-23 06:26:07

标签: mysql sql sql-server sql-server-2008 tsql

在sql server中,我有一个表格,其中包含的记录超过

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

现在我希望输出分组,每组都有最小值,所以输出应该像下面的1

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

4 个答案:

答案 0 :(得分:4)

  

现在我想要的一些变化在同一个表中   想要是前两个最大值

如果您使用的是SQL-Server,可以使用ROW_NUMBERDENSE_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

如果您还需要每empnos的最小/最大值,则可以使用OVER子句:

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

答案 1 :(得分:3)

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

答案 2 :(得分:0)

 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 allunion

答案 3 :(得分:0)

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

结果:

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