SQL 2个聚合列之间的百分比差异

时间:2014-05-14 18:48:50

标签: sql sql-server-2008

我不确定我的术语是否正确。我有这个问题:

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;

我想找到两个新(聚合?)列之间的百分比差异。原始列是varchar(2),两个varchar(4)列和一个varchar(3)列。

3 个答案:

答案 0 :(得分:0)

这是你可以做到的一种方式:

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_
)

答案 1 :(得分:0)

将此更改为条件聚合:

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;

注意使用十进制常量进行除法。 SQL Server对整数进行整数除法。

答案 2 :(得分:0)

这将给出sum1和sum2之间的差值,表示为相对于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

使用from子句中的派生表可以获得更清晰,更易读的SQL,因为您不会在整个地方复制聚合表达式。