Hi,I am currently converting a huge slow sql query that scans through a table and produces lots of totals for a customer. It currently defines lots of variables and then does a select per variable. This results in lots of table scans and really slow performance.I have re-written the query so it uses a single select into a derived table and then multiple case when statements to create the totalsegselect sum(case when value = 1 then 1 else 0 end) as Totalfrom ( select * from datatable where customer = 1 and date between @a and @b) as DerivedTable
This works great and runs in a fraction of a section compared to the other query. The problem I've come across now is that the old query does a select count(distinct value + value2)
in a few places. So far I haven't worked out how I can replicate the same thing in my single query.I guess my question would be: Is there anyway to write the BELOW code as a single query using only a single scan of the table @t ?declare @t table( forename varchar(10), surname varchar(10), id int)insert @t select 'Fred', 'Smith', 0 union all select 'Jane', 'Smith', 1 union all select 'Andy', 'Melon', 1 union all select 'Tim', 'Apple', 2 union all select 'Fred', 'Smith', 0select count(distinct(forename + surname)) as a from @t where id = 0select count(distinct(forename + surname)) as a from @t where id = 1select count(distinct(forename + surname)) as a from @t
Thanks for any help