2013-03-05 73 views
0

我試圖找出如何在這種情況下使用MAX()。 在此查詢的結果中,我有重複項,我只想找到一個最新記錄(這裏是日期:CL.CL_DATE_FROM),並通過db1.IDF和O.IDp對其進行重複數據刪除。SQL查詢 - 最大和重複

SELECT 
    db1.IDF as IDF, 
    O.IDp as IDP, 
    O.Action as Action, 
    U.USR_IDENT as Operator, 
    O.ID_T as ID_T, 
    OC.OC_MEMO as MEMO, 
    CONVERT(VARCHAR(10),CL.CL_DATE_FROM,120) as date, 
    CONVERT(VARCHAR(8),CL.CL_DATE_FROM,108) as time 
from OUTBOUND OC 
    join CALL CL on CL.CL_ID= OC.OC_CL_ID 
    join CAMPAIGN CA on CA.CA_ID = OC.OC_CA_ID 
    join STATUSES ATT on ATT.AS_ID = OC.OC_AS_ID 
    join USERS U on U.USR_ID = OC.OC_USR_ID 
    join Outbound_Z O on O.ID = OC.OC_CUS_ID 
    join db1.dbo.Clients db1 on db1.ID_T = O.ID_T 
where CL.CL_DATE_FROM BETWEEN '2013-03-05 00:00:00.000' AND '2013-03-05 23:59:59.000' 

回答

0

我會用row_number()此:

with t as (
    SELECT db1.IDF as IDF, O.IDp as IDP, O.Action as Action, U.USR_IDENT as Operator, 
      O.ID_T as ID_T, OC.OC_MEMO as MEMO, CONVERT(VARCHAR(10),CL.CL_DATE_FROM,120) as date, 
      CONVERT(VARCHAR(8),CL.CL_DATE_FROM,108) as time, 
      ROW_NUMBER() over (partition by db1.idf, o.idp order by cl.cl_date_from desc) as seqnum 
    from OUTBOUND OC 
     join CALL CL on CL.CL_ID= OC.OC_CL_ID 
     join CAMPAIGN CA on CA.CA_ID = OC.OC_CA_ID 
     join STATUSES ATT on ATT.AS_ID = OC.OC_AS_ID 
     join USERS U on U.USR_ID = OC.OC_USR_ID 
     join Outbound_Z O on O.ID = OC.OC_CUS_ID 
     join db1.dbo.Clients db1 on db1.ID_T = O.ID_T 
    where CL.CL_DATE_FROM BETWEEN '2013-03-05 00:00:00.000' AND '2013-03-05 23:59:59.000' 
    ) 
select * 
from t 
where seqnum = 1 

row_number()是窗口函數,它爲一組記錄分配一個連續編號。在這種情況下,這些組由兩個ID定義。排序是如此最近得到分配1.

順便說一句,像這樣的查詢重複可能是由連接引起的。不同的連接是多行,結果是值的笛卡爾積。您也可以調查以找出重複的原因並解決問題。

1

你應該能夠使用類似這樣的東西,將返回max(CL_DATE_FROM)每個CL_ID

SELECT 
    db1.IDF as IDF, 
    O.IDp as IDP, 
    O.Action as Action, 
    U.USR_IDENT as Operator, 
    O.ID_T as ID_T, 
    OC.OC_MEMO as MEMO, 
    CONVERT(VARCHAR(10),CL.MaxDate,120) as date, 
    CONVERT(VARCHAR(8),CL.MaxDate,108) as time 
from OUTBOUND OC 
join 
(
    select max(CL_DATE_FROM) MaxDate, 
     CL_ID 
    from CALL 
    where CL_DATE_FROM BETWEEN '2013-03-05 00:00:00.000' AND '2013-03-05 23:59:59.000' 
    group by CL_ID 
) CL 
    on CL.CL_ID= OC.OC_CL_ID 
join CAMPAIGN CA 
    on CA.CA_ID = OC.OC_CA_ID 
join STATUSES ATT 
    on ATT.AS_ID = OC.OC_AS_ID 
join USERS U 
    on U.USR_ID = OC.OC_USR_ID 
join Outbound_Z O 
    on O.ID = OC.OC_CUS_ID 
join db1.dbo.Clients db1 
    on db1.ID_T = O.ID_T