I'm building a report and I'm in a dilemma which path to follow to reach better performance.
I got a table where
COD | CTYPID | MNT
The above contains COD
as the primary key, type and amount
The report will contain each type as a column. Meaning one COD
will have 3 columns for each CTYPID
.
Which one is the best:
1-
Insert into #temp
Select sum(amount),CTYPID From table
Group by COD,CTYPIDz
Then I left join this table with my main table where CTYPID=1 Then another left join where CTYPID=2 and so one
2-
--insert in a temp table on multiple columns
insert into #temp
(Select sum(amount) column1,CTYPID From table where CTYPID=1
Group by COD)
Left join (Select sum(amount)column2 ,CTYPID From table where CTYPID=2
Group by COD)
Then join the above with my main table
One alternative option would be to do conditional aggregation:
insert into #temp
select
cod,
sum(case when ctypid = 1 then mnt else 0 end) mnt_ctypid1,
sum(case when ctypid = 2 then mnt else 0 end) mnt_ctypid2,
sum(case when ctypid = 3 then mnt else 0 end) mnt_ctypid3
from mytable
group by cod
For this query, you want an index on (cod, ctypid)
(which might be already there since this seems to - or should - be the primary key of your table).
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.