SQL DISTINCT列,第二标准为日期时间

时间:2018-12-27 00:21:52

标签: sql sql-server ssms

我刚刚开始在SQL Server Management Studio中学习SQL并深入研究。

我只需要唯一的DriverID,并且在过去3个月中有一个LogoffTime,标题如下。

到目前为止我所拥有的:

SELECT 
    Dr.DriverName, Dr.DriverNumber, Dr.DriverID, 
    DL.DriverID, DL.LogoffTime,
    ROW_NUMBER() OVER (PARTITION BY DL.DriverID ORDER BY DL.LogoffTime DESC) AS rn
FROM 
    Taxihistory.dbo.DriverLogon DL, Taxihistory.dbo.Driver Dr 
WHERE 
    DL.DriverID = Dr.DriverID
    AND DL.LogoffTime <= '20180931'
    AND rn = 1 
ORDER BY 
    DL.LogoffTime DESC;

我当前收到此错误:

  

第207条消息,第16级,状态1,第7行
  无效的列名“ rn”

3 个答案:

答案 0 :(得分:3)

如果要浏览CTE(公用表表达式)选项,则也可以使用CTE实现。您可以尝试以下操作:

WITH CTE AS (
SELECT dr.drivername,
                    dr.drivernumber,
                    dr.driverid,
                    dl.logofftime,
                    row_number() OVER (PARTITION BY dl.driverid
                                       ORDER BY dl.logofftime DESC) AS rn
                    FROM taxihistory.dbo.driverlogon dl
                         INNER JOIN taxihistory.dbo.driver dr
                                    ON dr.driverid = dl.driverid
                    WHERE dl.logofftime <= Convert(datetime, '2018-09-30') ) 

SELECT tbl.drivername,
       tbl.drivernumber,
       tbl.driverid,
       tbl.logofftime
FROM CTE tbl
WHERE tbl.rn = 1 
ORDER BY tbl.logofftime DESC;

答案 1 :(得分:0)

您不能在CREATE SEQUENCE PRS START 1; CREATE SEQUENCE BDX START 1; insert into your_table (object_num, code_name, other_data) values ( code_name||lpad(nextval(code_name)::char,3,'0') , code_name, other_data); 子句中使用列别名。您也不能在那里使用WHERE。您必须在子查询中用row_number()包装查询,然后从中选择。

row_number()

也建议使用显式联接语法。我确实希望SELECT x.drivername, x.drivernumber, x.driverid, x.logofftime FROM (SELECT dr.drivername, dr.drivernumber, dr.driverid, dl.logofftime, row_number() OVER (PARTITION BY dl.driverid ORDER BY dl.logofftime DESC) rn FROM taxihistory.dbo.driverlogon dl INNER JOIN taxihistory.dbo.driver dr ON dr.driverid = dl.driverid WHERE dl.logofftime <= '20180930') x WHERE x.rn = 1 ORDER BY x.logofftime DESC; 不是driverlogon.logofftime,而是某些日期/时间类型。

答案 2 :(得分:0)

您应该通过以下方式获得最近3个月到当前日期的登录信息:

SELECT Dr.DriverName, Dr.DriverNumber, Dr.DriverID, DL.DriverID, DL.LogoffTime
FROM Taxihistory.dbo.DriverLogon DL, 
INNER JOIN Taxihistory.dbo.Driver Dr ON DL.DriverID = Dr.DriverID
WHERE DL.LogOffTime < DATEADD(MONTH, -3, GETDATE())
ORDER BY DL.LogoffTime DESC;