如何按最近的日期分组?

时间:2015-06-23 19:54:16

标签: sql sql-server-2008-r2 subquery

我有一个HISTORY表,它有多行用于同一记录,我正在尝试获取最新的(最接近今天的日期)记录。我试图按最近的日期分组,但我遇到了困难。请查看下面的查询并告诉我。

SELECT DISTINCT *
FROM
  (SELECT etc.Complaint.Complaint_ID AS Complaint_ID
     FROM etc.Complaint) AS Qry1  
     LEFT JOIN
        (SELECT etc.Complaint.Complaint_ID AS Complaint_ID,
                o.Action_User AS Resolved_User,
                o.Action_Date AS LastActionDate
           FROM etc.Complaint 
           LEFT OUTER JOIN etc.History as o 
             ON SUBSTRING(Primary_Key,15,LEN(Primary_Key) - 15) = etc.Complaint.Complaint_ID 
            AND TABLE_NAME = 'Resolution' AND o.Field_Name = 'Resolved_Ind' 
            AND New_Value = 1) AS Qry2 
       ON Qry1.Complaint_ID = Qry2.Complaint_ID
    ORDER BY Qry1.Complaint_ID, MAX(Qry2.LastActionDate) 

2 个答案:

答案 0 :(得分:0)

这改变了帮助吗?

    SELECT DISTINCT *
    FROM
      (SELECT etc.Complaint.Complaint_ID AS Complaint_ID FROM etc.Complaint) AS Qry1  
         LEFT JOIN
            (SELECT etc.Complaint.Complaint_ID AS Complaint_ID,
                    o.Action_User AS Resolved_User,
                    o.Action_Date AS LastActionDate
               FROM etc.Complaint 
               LEFT OUTER JOIN 
                  (
                        SELECT SUBSTRING(Primary_Key,15,LEN(Primary_Key) - 15) as hist_Complaint_ID , MAX(Action_Date) as Action_Date
                        FROM etc.History
                        WHERE Field_Name = 'Resolved_Ind' 
                        GROUP BY SUBSTRING(Primary_Key,15,LEN(Primary_Key) - 15)
                  ) as o
                 ON o.hist_Complaint_ID = etc.Complaint.Complaint_ID 
                AND TABLE_NAME = 'Resolution' AND o.Field_Name = 'Resolved_Ind' 
                AND New_Value = 1) AS Qry2 
           ON Qry1.Complaint_ID = Qry2.Complaint_ID
        ORDER BY Qry1.Complaint_ID, Qry2.LastActionDate 

答案 1 :(得分:0)

您可以使用ROW_NUMBER和CTE来获取它:

WITH cte AS (
    SELECT etc.Complaint.Complaint_ID AS Complaint_ID,
                    o.Action_User AS Resolved_User,
                    o.Action_Date AS LastActionDate
                    row_number() over (partition by etc.Complaint.Complaint_ID order by o.Action_Date desc) AS rn
    FROM etc.Complaint 
    LEFT OUTER JOIN etc.History as o 
        ON SUBSTRING(Primary_Key,15,LEN(Primary_Key) - 15) = etc.Complaint.Complaint_ID 
    AND TABLE_NAME = 'Resolution' AND o.Field_Name = 'Resolved_Ind' 
    AND New_Value = 1
)

SELECT * FROM cte
WHERE rn = 1