首页  >  问答  >  正文

去除重复行,只保留最新的工作日志条目

<p>我创建了这个查询,它可以工作。问题是它显示了每个工作日志的行。我只需要每个事件的最新工作日志。</p> <pre class="brush:php;toolbar:false;">SELECT DISTINCT `HPD:Help Desk`.`Incident Number` AS Incident_Number, `HPD:Help Desk`.`Status` AS Status, `HPD:Help Desk`.`Priority` AS Priority, `HPD:Help Desk`.`Assigned Group` AS Assigned_Group, `HPD:Help Desk`.`Assignee` AS Assignee, `HPD:Help Desk`.`Submit Date` AS Submit_Date, `HPD:Help Desk`.`Last Modified Date` AS Last_Modified_Date, `HPD:Help Desk`.`Description` AS Description, `HPD:Help Desk`.`Submitter` AS Submitter, `HPD:Search-Worklog`.`Worklog Description` AS Worklog_Description, `HPD:Search-Worklog`.`Work Log ID` AS Work_Log_ID FROM `HPD:Help Desk` INNER JOIN `HPD:Search-Worklog` on (`HPD:Search-Worklog`.`InstanceId` = `HPD:Help Desk`.`InstanceId`) WHERE (`HPD:Help Desk`.`Status` in ('Assigned','Pending','In Progress') And `HPD:Help Desk`.`Submit Date` >= $__from/1000 and `HPD:Help Desk`.`Submit Date` <= $__to/1000) ORDER BY `HPD:Help Desk`.`Submit Date` ASC LIMIT 20</pre> <p>我尝试过HPD:Help Desk、HPD:Worklog和HPD:Search-Worklog表单。我还尝试使用CASE语句只显示每个事件的最新/最大工作日志ID,但没有成功。我确定我漏掉了一些明显/简单的东西。</p>
P粉916760429P粉916760429460 天前645

全部回复(1)我来回复

  • P粉252423906

    P粉2524239062023-08-11 12:45:29

    假设使用支持窗口函数的最新版本的MySQL(或其变体),获取“最新”的一种非常有效的方法是使用row_number() over()。在over子句中使用partition by来控制什么会触发行编号重置,并使用order by来控制分区中获得行号1的行。现在,要获取“最新”的需要在worklog表中有一列来实现这个功能 - 我假设有一个时间戳列(worklog_entry_date存在于该表中(worklog_entry_date),您需要替换实际确定“最新”的列)。将当前查询嵌套一层,以便您可以过滤行号为1的情况 - 这些将是“最新”的行:

    SELECT
        *
    FROM (
        SELECT
              h.`Incident Number` AS Incident_Number
            , h.`Status` AS STATUS
            , h.`Priority` AS Priority
            , h.`Assigned Group` AS Assigned_Group
            , h.`Assignee` AS Assignee
            , h.`Submit Date` AS Submit_Date
            , h.`Last Modified Date` AS Last_Modified_Date
            , h.`Description` AS Description
            , h.`Submitter` AS Submitter
            , w.`Worklog Description` AS Worklog_Description
            , w.`Work Log ID` AS Work_Log_ID
            , row_number() over(partition by h.`Incident Number`
                                order by w.worklog_entry_date DESC) as rn
        FROM `HPD: HELP Desk` h
        INNER JOIN `HPD: Search - Worklog` w ON w.`InstanceId` = h.`InstanceId`
        WHERE h.`Status` IN ('Assigned', 'Pending', 'In Progress')
            AND h.`Submit Date` >= $_ _from / 1000
            AND h.`Submit Date` <= $_ _to / 1000
        ) d
    WHERE d.rn = 1
    ORDER BY
          d.`Submit Date` ASC 
    LIMIT 20

    注意:当行编号存在时,您不需要使用select distinct - 一般情况下尽量避免使用它。此外,请自己使用表别名来简化代码。

    回复
    0
  • 取消回复