2

在 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

4 回答 4

4

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

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

演示

如果您还想要每个 的 Min-/Max 值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

演示

于 2013-07-23T06:47:48.037 回答
3
Select empnos ,  Max(date) from TableName Group by empnos 
Union
Select empnos ,  Min(date) from TableName Group by empnos order by empnos 

Sql 小提琴演示

于 2013-07-23T06:29:17.937 回答
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
于 2013-07-23T11:09:06.617 回答
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 all或者union可以根据您的要求使用

于 2013-07-23T06:34:31.443 回答