4

对于每个不同的名称,我想选择具有最早时间戳(或 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
4

2 回答 2

5
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
于 2012-07-30T18:59:58.693 回答
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
于 2012-07-30T18:58:26.987 回答