performance - Efficient use of SQL GROUP BY, SUM, COUNT -
i have table of products sales may follows:
product | amount | ptype | pdate p1 | 1.00 | sale | 01/01 p1 | 2.00 | base | 01/02 p2 | 1.50 | sale | 02/03 p3 | 5.25 | base | 10/10
and build table shows 1 product per row, sum of amounts, if product unique show type else show type 'var', if product unique show date else show date null. result follows:
product | total | ptype | pdate p1 | 3.00 | var | (null) p2 | 1.50 | sale | 02/03 p3 | 5.25 | base | 10/10
i accomplishing result need doing following:
select distinct product ,(select sum(amount) t b group b.product having a.product = b.product ) total ,(select case when count(*) = 1 a.ptype else 'var' end t b group b.product having a.product = b.product) ptype ,(select case when count(*) = 1 a.pdate else null end t b group b.product having a.product = b.product) pdate t
but know if there more efficient way accomplishes same result.
there no need use form of subquery or inline view. depending on sophistication of database engine, constructs negatively impact performance.
here requested, , should reliably give result single scan of table on primitive sql engine.
select product, sum(amount) amount, case when count(*)=1 min(ptype) else 'var' end ptype, case when count(*)=1 min(pdate) else null end pdate t group product
the following not requested, think may closer looking for. reports ptype var or pdate null if there multiple distinct values making aggregate.
i've added pcount column can still identify singlet aggregates, if both ptype , pdate not nulll.
select product, sum(amount) amount, count(*) pcount, case when count(distinct ptype)=1 min(ptype) else 'var' end ptype, case when count(distinct pdate)=1 min(pdate) else null end pdate t group product
Comments
Post a Comment