SQL:为每个不同的值选择三行

时间:2012-07-30 18:44:41

标签: sql select timestamp where

对于每个不同的Name,我想选择具有最早time_stamp的前三行(或UNIXTIME中的最小数字)。什么是正确的查询?

开始表:

Name         Log-in Time
--------     -----------------
Don          05:30:00
Don          05:35:32
Don          07:12:43
Don          09:52:23
Don          05:32:43
James        03:30:00
James        03:54:23
James        09:51:54
James        14:43:34
James        43:22:11
James        59:43:33
James        20:12:11
Mindy        05:32:22
Mindy        15:14:44
Caroline     10:02:22
Rebecca      20:43:32

结束表:

Name         Log-in Time
--------     -----------------
Don          05:30:00
Don          05:35:32
Don          07:12:43
James        03:30:00
James        03:54:23
James        09:51:54
Mindy        05:32:22
Mindy        15:14:44
Caroline     10:02:22
Rebecca      20:43:32

2 个答案:

答案 0 :(得分:3)

WITH Table (Name, LoginTime, Row) AS
(
    SELECT 
       Name,
       LoginTime,
       ROW_NUMBER() OVER (PARTITION BY Name ORDER BY LoginTime)
    FROM SomeTable
)
SELECT 
   Name,
   LoginTime
FROM Table
WHERE 
   Row <= 3

答案 1 :(得分:0)

ansi标准方法实际上可以使用以下内容:

http://www.sqlfiddle.com/#!2/b814d/15

SELECT
    NAME
    , LOGIN
FROM (
    SELECT 
        test_first.NAME,
        test_first.LOGIN,
        COUNT(*) CNT
    FROM 
        TABLE_NAME test_first
    LEFT OUTER JOIN 
        TABLE_NAME test_second
        ON (test_first.NAME = test_second.NAME)
    WHERE 
        test_first.LOGIN <= test_second.LOGIN
    GROUP BY  
        test_first.NAME, test_first.LOGIN) test_order
WHERE 
    test_order.CNT <= 3
ORDER BY 
    NAME ASC, LOGIN ASC