SQL Server 2012 - 在DISTINCT上使用ROW_NUMBER()

时间:2017-03-23 05:30:14

标签: sql sql-server sql-server-2012

我在下面有一个查询。

SELECT DISTINCT
    FORMAT(CAST(SchedTi AS DATETIME),'hh:mm tt') AS SchedTimeIn,
    FORMAT(CAST(SchedTO AS DATETIME),'hh:mm tt') AS SchedTimeOut
FROM 
    tblemployee_schedule
ORDER BY 
    SchedTimeIn

返回此结果集:

SchedTimeIn  SchedTimeOut
01:00 AM     09:00 AM
01:00 AM     10:00 AM
01:00 AM     10:00 PM
01:15 AM     05:15 AM
01:15 AM     10:15 AM
01:30 AM     05:30 AM
01:30 PM     10:30 PM
01:45 AM     05:45 AM

我想要的结果是:

SchedTimeIn  SchedTimeOut ROWNUM
01:00 AM     09:00 AM     1
01:00 AM     10:00 AM     2
01:00 AM     10:00 PM     3
01:15 AM     05:15 AM     4
01:15 AM     10:15 AM     5
01:30 AM     05:30 AM     6
01:30 PM     10:30 PM     7
01:45 AM     05:45 AM     8

我尝试了以下查询:

SELECT DISTINCT
    ROW_NUMBER() OVER(ORDER BY SchedTi),
    FORMAT(CAST(SchedTi AS DATETIME),'hh:mm tt') AS SchedTimeIn,
    FORMAT(CAST(SchedTO AS DATETIME),'hh:mm tt') AS SchedTimeOut
FROM 
    tblemployee_schedule
ORDER BY 
    SchedTimeIn

但是它返回了太多的冗余行和NULL值。

提前谢谢。

2 个答案:

答案 0 :(得分:3)

尝试下面的一个,

SELECT * ,ROW_NUMBER() OVER(ORDER BY SchedTimeIn) AS ROWNUM
FROM    (
    SELECT DISTINCT
    FORMAT(CAST(SchedTi AS DATETIME),'hh:mm tt') AS SchedTimeIn,
    FORMAT(CAST(SchedTO AS DATETIME),'hh:mm tt') AS SchedTimeOut
    FROM tblemployee_schedule
)   AS  D
ORDER BY ROWNUM

在您的查询ROW_NUMBER()中为每条记录生成一个新的序列号,因此DISTINCT密钥不会因为相同而产生错误,这就是为什么您获得了太多冗余记录的原因。因此,您可以在外部查询中使用ROW_NUMBER()来克服此问题。

答案 1 :(得分:1)

主要问题是你只问一部分问题, 在firstplace中使用distinct,order by,row_number在同一查询中似乎是错误的。 仅使用分区功能就足够了。

使用您的查询的任何方式,

select * 
,ROW_NUMBER()over(order by SchedTimeIn)rn
FROM
(
SELECT DISTINCT
FORMAT(CAST(SchedTi AS DATETIME),'hh:mm tt') AS SchedTimeIn,
FORMAT(CAST(SchedTO AS DATETIME),'hh:mm tt') AS SchedTimeOut
FROM tblemployee_schedule
ORDER BY SchedTimeIn
)tbl