【问题标题】:Query to find the percentage difference of each row in sql server查询sql server中每一行的百分比差异
【发布时间】:2016-03-14 14:30:29
【问题描述】:

我有一张桌子,里面有一些列。我想编写一个遍历每一行的查询,并找到与所选行中的列匹配的所有行的总数,并找到与 2 列匹配的所有行的计数。有了这两个值,我想找到百分比差异并将它们打印为 column1, percent(query1(column2)/query2(column2 and column3))。

下面是我写的查询

    SELECT DISTINCT (t2.column1)
    ,(
        SELECT count(DISTINCT column2)
        FROM table1 t1
        WHERE t1.column1 = t2.column1
        ORDER BY column2
        ) AS total_count
    ,(
        SELECT count(DISTINCT column2)
        FROM table1 t1
        WHERE t1.column1 = t2.column1
            AND column3 IN (
                10
                ,20
                )
        ORDER BY column1
            ,column2
            ,column3
        ) AS column3_count
FROM table1 t2;

上述查询有效,但处理时间较长。

我想要它

   SELECT DISTINCT (column1)
    ,percentage(query1 that matches ALL rows WITH column1 / query2 that match ALL rows WITH column1
        AND SOME other CONSTRAINT)
FROM TABLE t1

我也想优化上面的查询。请告诉我

谢谢

【问题讨论】:

    标签: sql sql-server


    【解决方案1】:

    我认为您只需要条件聚合。对于计数:

    select t1.column1,
           count(distinct column2) as num_column2,
           count(distinct case when column3 in (10, 20) then column2 end) as num_column2_column3
    from table1 t1
    group by t1.column1;
    

    我不明白百分比的计算方法,但它似乎是基于这些数字。

    【讨论】:

      【解决方案2】:
      select t1.column1,
             count(distinct column2) as num_column2,
             count(distinct case when column3 in (10, 20) then column2 end) as num_column2_column3
      from table1 t1
      group by t1.column1;
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-10-03
        • 1970-01-01
        • 1970-01-01
        • 2016-04-09
        • 1970-01-01
        相关资源
        最近更新 更多