如何删除重复项并合并帐户类型?
我有一个根据帐户类型报告重复电话的通话记录。
例如:
Telephone | Account Type
304-555-6666 | R
304-555-6666 | C
在示例中,幸存的副本将是:
Telephone | Account Type
304-555-6666 | B
警告,不保证重复的手机有多种帐户类型。
示例:
Telephone | Account Type
999-888-6666 | R
999-888-6666 | R
因此,幸存的副本应该是:
Telephone | Account Type
999-888-6666 | R
如何删除重复项并同时重置帐户类型?
--
-- Remove Duplicate Recordings
--
SELECT * FROM (
SELECT i.dateofcall ,
i.recordingfile ,
i.telephone ,
s.accounttype ,
ROW_NUMBER() OVER (PARTITION BY i.telephone ORDER BY i.dateofcall DESC) AS 'RANK' ,
COUNT(i.telephone) OVER (PARTITION BY i.telephone) AS 'MAXCOUNT'
FROM #myactions i
LEFT JOIN #myphone s ON s.interactionID = i.Interactionid
) x
WHERE [RANK] = [MAXCOUNT]
答案 0 :(得分:1)
试试这个?
select
x.dateofcall
, x.recordingfile
, x.telephone
, case when count(*) > 2 then 'B' else max(x.accounttype) end accounttype
(
select
i.dateofcall
, i.recordingfile
, i.telephone
, s.accounttype
from
#myactions i
LEFT JOIN #myphone s ON s.interactionID = i.Interactionid
group by
i.dateofcall
, i.recordingfile
, i.telephone
, s.accounttype
) x
group by
x.dateofcall
, x.recordingfile
, x.telephone
答案 1 :(得分:1)
基本上,您需要将业务检查放在外部的案例陈述中。
编辑:我还添加了B,R和C的逻辑。还做了一个sql小提琴 - 小提琴 - http://sqlfiddle.com/#!6/b5ef5/7
SELECT
x.dateofcall,
x.recordingfile,
x.telephone,
COALESCE(
CASE WHEN x.maxcount>1 AND value>x.maxcount AND value<(2*x.maxcount) THEN 'B' ELSE NULL END,
CASE WHEN x.maxcount>1 AND value= (2*x.maxcount) THEN 'C' ELSE NULL END,
CASE WHEN x.maxcount>1 AND value= x.maxcount THEN 'R' ELSE NULL END,
x.accounttype ) as accounttype,
x.rank,
x.maxcount
FROM (
SELECT i.dateofcall ,
i.recordingfile ,
i.telephone ,
s.accounttype ,
ROW_NUMBER() OVER (PARTITION BY i.telephone ORDER BY i.dateofcall DESC) AS 'RANK' ,
COUNT(i.telephone) OVER (PARTITION BY i.telephone) AS 'MAXCOUNT',
SUM(CASE WHEN s.accounttype LIKE 'R' THEN 1 ELSE 2 END) OVER (PARTITION BY i.telephone) as Value
FROM
myactions i LEFT JOIN myphone s
ON s.interactionID = i.Interactionid
) x
WHERE [RANK] = [MAXCOUNT]
答案 2 :(得分:1)
SELECT * FROM (
SELECT i.dateofcall ,
i.recordingfile ,
i.telephone ,
s.accounttype ,
ROW_NUMBER() OVER (PARTITION BY i.telephone ORDER BY i.dateofcall DESC) AS 'RANK' ,
COUNT(i.telephone) OVER (PARTITION BY i.telephone) AS 'MAXCOUNT',
DENSE_RANK() OVER ( PARTITION BY i.telephone ORDER BY s.accounttype DESC ) AS 'ContPhone'
FROM #myactions i
LEFT JOIN #myphone s ON s.interactionID = i.Interactionid
) x
WHERE [RANK] = [MAXCOUNT]