0

我试图找出在这种情况下如何使用 MAX()。在此查询的结果中,我有重复项,我只想找到一个最新记录(这里是日期:CL.CL_DATE_FROM)并通过 db1.IDF 和 O.IDp 对其进行重复数据删除。

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'
4

2 回答 2

1

您应该能够使用与此类似的东西,这将返回max(CL_DATE_FROM)for each 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
于 2013-03-05T15:45:35.373 回答
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。

顺便说一句,像这样的查询中的重复可能是由连接引起的。不同的连接是多行,结果是值的笛卡尔积。您还可以进行调查以找出重复的原因并在那里解决问题。

于 2013-03-05T15:51:57.130 回答