sql server - SQL: Filter records based on record creation date and other criteria -


i struggling find better solution pick unique records user call data table. table structure follows:

select [marketname],        [websitename] ,        [id] ,        [userid],        [creationdate],        [callduration],        [fromphone] ,        [tophone],        [isanswered],        [source] [dbo].[usercalldata] 

there multiple entries in table different , same id's. wanted check if [fromphone] , [tophone] exists multiple times within last 3 months, if yes, wanted pick first record columns based on [creationdate], count number of occurrences totalcallcount , sum totalcallduration single record. if [fromphone] , [tophone] not occur multiple times, wanted pick columns such. have been able put partial query below. doesn't return columns without including in group clause , doesn't satisfy entire criteria. on highly appreciated.

select  [fromphone],          min([creationdate]),         [tophone],          marketname,          count(*) totalcallcount ,          sum(callduration) totalcallduration  [dbo].[usercalldata]  [creationdate] >= dateadd(month, -3, getdate()) group  [fromphone],[tophone], marketname  having count([fromphone]) > 1 , count([tophone]) >1 

try use row_number()

;with cte (     select *, row_number() over(partition fromphone, tophone order creationdate) rn     usercalldata     creationdate >= dateadd(month, -3, getdate()) ), cte_totals (     select c1.fromphone, c1.tophone, count(*) totalcallcount, sum(callduration) totalcallduration     cte c1     exists(select * cte c2 c1.fromphone = c2.fromphone , c1.tophone = c2.tophone , c2.rn > 1)     group c1.fromphone, c1.tophone ) select c1.*, totalcallcount, totalcallduration cte c1     inner join cte_totals c2 on c1.fromphone = c2.fromphone , c1.tophone = c2.tophone c1.rn = 1  

i wrote query right in here can have mistakes or mistypes, main idea might clear.


Comments

Popular posts from this blog

commonjs - How to write a typescript definition file for a node module that exports a function? -

openid - Okta: Failed to get authorization code through API call -

thorough guide for profiling racket code -