Question

I am unsure if my terminology is correct. I have this query:

select (select count(*)
        from table1
        where column1 = 'x' and column2 = 'y' and column3 = 'z'
       ) as new_column1,
       (select count(*) 
        from table 1
        where column1 = 'x' and column2 = 'y' and column3 = 'z'
       ) as new_column2;

I would like to find the percentage difference between the two new (aggregate?) columns. The original columns are varchar(2),two varchar(4) columns, and a varchar(3) column.

Was it helpful?

Solution

This will give you the delta between sum1 and sum2, expressed as a percentage relative to sum2:

select sum1      = s.sum1      ,
       sum2      = s.sum2      ,
       delta     = sum1 - sum2 ,
       delta_pct = 100.0 * ( sum1 - sum2 ) / sum2
from ( select sum1 = sum(case when t.c1='a' and t.c2='b' and t.c3='c' then 1 else 0 end) ,
              sum2 = sum(case when t.c1='x' and t.c2='y' and t.c3='z' then 1 else 0 end)
       from table1 t
     ) s

using the derived table in the from clause makes for cleaner, more readable SQL as you're not duplicating the aggregation expressions all over the place.

OTHER TIPS

Here's one way you could do it:

select 
new_column1,
new_,
new_column1 / new_ * 100  as PercentDiff
from
(
    select (select count(*)
            from table1
            where column1 = 'x' and column2 = 'y' and column3 = 'z'
           ) as new_column1,
           (select count(*) 
            from table1
            where column1 = 'x' and column2 = 'y' and column3 = 'z'
           ) as new_
)

Change this to conditional aggregation:

select sum(case when column1 = 'x' and column2 = 'y' and column3 = 'z' then 1
                else 0
           end) new_column1,
       sum(case when column1 = 'x' and column2 = 'y' and column3 = 'z' then 1
                else 0
           end) new_column2,
       (sum(case when column1 = 'x' and column2 = 'y' and column3 = 'z' then 1.0
                 else 0.0
            end) /
        sum(case when column1 = 'x' and column2 = 'y' and column3 = 'z' then 1.0
                 else 0.0
            end)
       ) ratio
from table1;

Notice the use of decimal constants for the division. SQL Server does integer division on integers.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top