如何在内部连接表上使用MAX在SQL中使用不同的数据

时间:2011-09-01 08:07:09

标签: sql sql-server-2008

我使用此代码根据max update_date获取不同的列。但是我仍然为同一个tel_number获得大约4或5个status_ids。我希望最大更新日期只占用最后一个日期...我的代码当前没有这样做。有人可以帮助我吗

SELECT  DISTINCT t.Tel_Number,
        t.Entity_ID,
        t.Datasource,
        t.Datasource_Number,
        t.UpdateDate, 
        t.DataDate, 
        t.Telephone_ID,
        t.Status_Id, 
        t.DateInserted,
        t.ProcessName,
        c.Status_Id AS CurrentCe_Status_ID,
        s.StatusType AS CurrentCe_StatusType,
        s.Description AS CurrentCe_Status_Description,
        MAX(c.Update_Date) AS CurrentCe_Status_Date

FROM   
    Wrk.dbo.tel_trsn t WITH (NOLOCK) INNER JOIN CrWec.dbo.teldet d WITH (NOLOCK)
    ON d.Tel_Number = t.Tel_Number
    AND d.Entity_Id = t.Entity_ID
    INNER JOIN   CrWec.dbo.status c WITH (NOLOCK)
    ON c.Entity_Id = t.Entity_ID
    INNER JOIN CrWec.dbo.statusType s WITH (NOLOCK)
    ON s.Status_Id = c.Status_Id
GROUP BY t.Tel_Number,
        t.Entity_ID,
        t.Datasource,
        t.Datasource_Number,
        t.UpdateDate, 
        t.DataDate, 
        t.Telephone_ID,
        t.Status_Id, 
        t.DateInserted,
        t.ProcessName,
        c.Status_Id,
        s.StatusType,
        s.Description

1 个答案:

答案 0 :(得分:0)

由于您没有指定任何密钥是什么,我尽力使用查询。实际上,如果你的键值只是Tel_Number,Entity_ID,Datasource,那么你只需要对ROW_NUMBER函数中的那3列进行分区(或者需要很多)。

;with MaxUpdateDate as (
    SELECT  t.Tel_Number,
            t.Entity_ID,
            t.Datasource,
            t.Datasource_Number,
            t.UpdateDate, 
            t.DataDate, 
            t.Telephone_ID,
            t.Status_Id, 
            t.DateInserted,
            t.ProcessName,
            c.Status_Id AS CurrentCe_Status_ID,
            s.StatusType AS CurrentCe_StatusType,
            s.Description AS CurrentCe_Status_Description,
            c.Update_Date AS CurrentCe_Status_Date,
            ROW_NUMBER() OVER (
                PARTITION BY 
                    t.Tel_Number,
                    t.Entity_ID,
                    t.Datasource,
                    t.Datasource_Number,
                    t.UpdateDate, 
                    t.DataDate, 
                    t.Telephone_ID,
                    t.Status_Id, 
                    t.DateInserted,
                    t.ProcessName,
                    c.Status_Id,
                    s.StatusType,
                    s.Description 
                ORDER BY 
                    c.Update_Date DESC) as 'RowNum'
        FROM   
            Wrk.dbo.tel_trsn t WITH (NOLOCK) 
            INNER JOIN CrWec.dbo.teldet d WITH (NOLOCK)
                ON  d.Tel_Number = t.Tel_Number
                    AND d.Entity_Id = t.Entity_ID
            INNER JOIN CrWec.dbo.status c WITH (NOLOCK)
                ON  c.Entity_Id = t.Entity_ID
            INNER JOIN CrWec.dbo.statusType s WITH (NOLOCK)
                ON  s.Status_Id = c.Status_Id
)

SELECT
    *
FROM
    MaxUpdateDate
WHERE
    RowNum = 1