sql server - SQL JOIN doubling values -


i have 2 temp tables following data:

temp_aht

enter image description here

temp_1

enter image description here

i use query join 2 tables on column incident:

    select         count(distinct a.incident) nr_of_tickets        ,a.[service]       ,sum(case when a.status_switch  in ('assigned » in progress','assigned » pending','assigned » resolved','assigned » closed') a.totalseconds else null end) assignedtime       ,sum(case when a.status_switch  in ('in progress » assigned','in progress » assigned','in progress » pending','in progress » resolved') a.totalseconds else null end) progresstime       ,sum(case when a.status_switch  in ('pending » assigned','pending » in progress') a.totalseconds else null end) pendingtime       ,sum(b.creation) creation       ,sum(b.[call duration]) [call duration]   ##temp_aht inner join ##temp_1 b on a.incident = b.incident_id  group a.[service],b.creation,b.[call duration] 

if join tables above query sums won't correct. think because in both tables have multiple rows same incident id.

but how can join table , take first row ##temp_1 if match found ?

the problem have multiple rows each incident in both tables. further complicated fact joining on 1 column (incident) , aggregating (service).

then, group by includes aggregated columns b table, doesn't make sense.

the solution aggregate both tables before doing join. think want:

select sum(nr_of_tickets), a.[service],        sum(assignedtime) assignedtime,        sum(progresstime) progresstime,        sum(pendingtime) pendingtime,        sum(b.creation) creation,        sum(b.[call duration]) [call duration]  (select a.service, count(distinct a.incident) nr_of_tickets,              sum(case when a.status_switch  in ('assigned » in progress','assigned » pending','assigned » resolved','assigned » closed') a.totalseconds end) assignedtime              sum(case when a.status_switch  in ('in progress » assigned','in progress » assigned','in progress » pending','in progress » resolved') a.totalseconds end) progresstime,              sum(case when a.status_switch  in ('pending » assigned','pending » in progress') a.totalseconds end) pendingtime       ##temp_aht       group a.incident, a.service      ) inner join      (select b.incident,               sum(b.creation) creation,              sum(b.[call duration]) [call duration]       ##temp_1 b       group b.incident      ) b      on a.incident = b.incident_id group a.[service] 

Comments

Popular posts from this blog

sequelize.js - Sequelize group by with association includes id -

android - Robolectric "INTERNET permission is required" -

java - Android raising EPERM (Operation not permitted) when attempting to send UDP packet after network connection -