问题
I know this question is asked frequently here but I have some different requirements.
I want to get this output. I am getting this also with my logic but can this can be done in more simple and optimised way. To run this query faster.
Here is my query:
select
ISNULL('PortFolio Code: '+a.CPORTFOLIOCODE,'Grand Total') as [PortFolio Code],
COUNT(SZCUSTOMERNO) as [Accounts],
CAST(COUNT(SZCUSTOMERNO) * 100 / (Select COUNT(SZCUSTOMERNO)
from dbo.COL_TRN_AGREEMENT)
as nvarchar(50))+' %' as [%],
sum(case when a.SZBUCKETCODE =1 then a.FOSAMT else 0 end ) as [Bucket :1],
sum(case when a.SZBUCKETCODE =2 then a.FOSAMT else 0 end ) as [Bucket :2],
sum(case when a.SZBUCKETCODE =3 then a.FOSAMT else 0 end ) as [Bucket :3],
sum(a.FOSAMT) as [All Buckets]
from
dbo.COL_TRN_AGREEMENT a
group by
a.CPORTFOLIOCODE with rollup
I am getting this output
Can this be done using simple logic with faster execution or this is the simplest way.
回答1:
Here is an approach, may not be faster, but you still have a choise to compare.
declare @cnt int
Select @cnt = COUNT(SZCUSTOMERNO) from dbo.COL_TRN_AGREEMENT
;with
matrix (SZBUCKETCODE,Bucket_1,Bucket_2,Bucket_3) as
(select 1,1,0,0 union
select 2,0,1,0 union
select 3,0,0,1)
select isnull('PortFolio Code: '+a.CPORTFOLIOCODE,'Grand Total') as [PortFolio Code],
COUNT(SZCUSTOMERNO) as [Accounts],
cast(COUNT(SZCUSTOMERNO)*100/@cnt as nvarchar(50))+' %' as [%],
sum(a.FOSAMT*m.Bucket_1) as [Bucket :1],
sum(a.FOSAMT*m.Bucket_2) as [Bucket :2],
sum(a.FOSAMT*m.Bucket_3) as [Bucket :3],
sum(a.FOSAMT) as [All Buckets]
from dbo.COL_TRN_AGREEMENT a
join matrix m
on m.SZBUCKETCODE = a.SZBUCKETCODE
group by a.CPORTFOLIOCODE with rollup
来源:https://stackoverflow.com/questions/25986902/query-optimisation-in-sql-server-2008-r2