SQL Count Distinct Rows

时间:2016-08-04 22:28:46

标签: sql distinct

有下表。

Date    Direction   Market  Time
    10/17/2016  SB  GRUJFK  22:05:00
    10/18/2016  SB  GRUJFK  22:05:00
    10/19/2016  SB  GRUJFK  22:05:00
    10/20/2016  SB  GRUJFK  22:05:00
    10/21/2016  SB  GRUJFK  22:05:00
    10/23/2016  SB  GRUJFK  23:20:00
    10/23/2016  SB  GRUJFK  22:30:00
    10/24/2016  SB  GRUJFK  22:30:00
    10/25/2016  SB  GRUJFK  22:30:00
    10/26/2016  SB  GRUJFK  22:30:00
    10/27/2016  SB  GRUJFK  22:30:00
    10/28/2016  SB  GRUJFK  22:30:00

我想计算不同列中的不同行但是按顺序为重复的行分配一个数字(从1..n开始)

    Date    Direction   Market  Time   Count
10/17/2016  SB  GRUJFK  22:05:00    1
10/18/2016  SB  GRUJFK  22:05:00    1
10/19/2016  SB  GRUJFK  22:05:00    1
10/20/2016  SB  GRUJFK  22:05:00    1
10/21/2016  SB  GRUJFK  22:05:00    1
10/23/2016  SB  GRUJFK  23:20:00    1
10/23/2016  SB  GRUJFK  22:30:00    2
10/23/2016  SB  GRUJFK  23:30:00    3
10/25/2016  SB  GRUJFK  22:30:00    1
10/26/2016  SB  GRUJFK  22:30:00    1
10/27/2016  SB  GRUJFK  22:30:00    1
10/28/2016  SB  GRUJFK  22:30:00    1

所以在这种情况下,只有10/23/2016有3个不同的值。因此,将1分配给第一个匹配项,将2分配给第二个匹配项等

我尝试了以下

select 
        departureDate,
DIRECTION, LEG,  SCHD_LEG_DEP_TM, count(SCHD_LEG_DEP_TM) over (partition by departureDate)
 from table3mirs mirs 
        INNER JOIN sys_calendar.calendar
        ON calendar_date = mirs.departureDate

 where leg='GRUJFK'
 group by 1,2,3,4

但是

    Date    Direction   Market  Time   Count
10/17/2016  SB  GRUJFK  22:05:00    1
10/18/2016  SB  GRUJFK  22:05:00    1
10/19/2016  SB  GRUJFK  22:05:00    1
10/20/2016  SB  GRUJFK  22:05:00    1
10/21/2016  SB  GRUJFK  22:05:00    1
10/23/2016  SB  GRUJFK  23:20:00    3
10/23/2016  SB  GRUJFK  22:30:00    3
10/23/2016  SB  GRUJFK  23:30:00    3
10/25/2016  SB  GRUJFK  22:30:00    1
10/26/2016  SB  GRUJFK  22:30:00    1
10/27/2016  SB  GRUJFK  22:30:00    1
10/28/2016  SB  GRUJFK  22:30:00    1

有什么想法吗?谢谢你的帮助!

2 个答案:

答案 0 :(得分:1)

如果您正在使用MSSQL(我认为您可能会获得分区),您可以试试这个。

select 
        departureDate,
DIRECTION, LEG,  SCHD_LEG_DEP_TM, count(DISTINCT SCHD_LEG_DEP_TM) over (partition by departureDate)
 from table3mirs mirs 
        INNER JOIN sys_calendar.calendar
        ON calendar_date = mirs.departureDate

 where leg='GRUJFK'
 group by 1,2,3,4

答案 1 :(得分:0)

看起来你只需要row_number ..

SELECT  departureDate ,
        DIRECTION ,
        LEG ,
        SCHD_LEG_DEP_TM ,
        ROW_NUMBER() OVER ( PARTITION BY departureDate ORDER BY SCHD_LEG_DEP_TM )
FROM    table3mirs mirs
        INNER JOIN sys_calendar.calendar ON calendar_date = mirs.departureDate
WHERE   leg = 'GRUJFK'
GROUP BY 1 ,
        2 ,
        3 ,
        4