2013-07-23 131 views
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 

回答

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

+0

thanxs現在BT有我需要的一些變化是在同一張表我想要的是前兩個最大值 – user2583182

+1

@ user2583182烏爾使用我的SQL或SQL Server –

+0

A1 \t 7月19日 - 13 A2 \t 7月19日 - 13 A3 \t 7月19日 - 13 A1 \t 20-07-13 A1 \t 20-07-13 A2 \t 20-JUL-13 A3 \t 20-JUL-13 A1 \t 21-JUL-13 A1 \t 21-JUL-13 A1 \t 21-JUL-13 A1 \t 21-JUL-13 A2 \t 21-Jul-13 a2 \t 21-Jul-13 a2 \t 21-Jul-13 a3 \t 21-Jul-13 – user2583182

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可以根據您的需要而定

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的MIN- /最大值,您可以使用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

+0

這一個是針對top 2最大值,但是top 2最大值和最大值怎麼樣? – hims056

+0

這如何給max()和min()? '它只給出最大值和第二最大值'na? – Nithesh

+0

@ hims056:這是他改變的要求(_「需求有一些變化」)的答案。看看他的評論[阿米特辛格的答案](http://stackoverflow.com/a/17802925/284240)。 –

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