具有百分比条件的不同SQL选择

时间:2016-05-24 17:06:30

标签: sql postgresql

我有一个PostgreSQL表,如下所示,

portal   partner     location_quality 
38       10060       46
38       10060       46
38       5586        90
4        10060       90
23       11843       10
38       12594       90
38       10438       50
38       10060       90
23       10438       46
36       12660       90
23       12594       50

对于每对门户网站&合作伙伴location_quality的范围是0到100.我想要所有不同的门户网站&如果每对的location_quality的90%大于50,则为partner。

我想得到所有不同的门户网站&如果90%的location_quality大于50,那么合作伙伴对。有人可以帮忙吗?

3 个答案:

答案 0 :(得分:2)

  1. 对行进行分组
  2. agregad with max
  3. 过滤

    SELECT
     portal,
     partner,
     max(location_quality) as location_quality
    FROM
     table01
    GROUP BY
     portal,
     partner
    HAVING
     max(location_quality) > 50
    
  4. 现在解决您的问题

    1. 统计所有
    2. 大于50时计算
    3. 取百分比并比较是否是90%

      SELECT
       portal,
       partner,
       count(CASE WHEN location_quality > 50 THEN 1 END) * 100 /  count(location_quality ) as percent_above
      FROM
       table01
      GROUP BY
       portal,
       partner
      HAVING
       count(CASE WHEN location_quality > 50 THEN 1 END) * 100 /  count(location_quality ) > 90;
      

答案 1 :(得分:0)

我可能会误解,但这就是90%位置质量的意思吗?

SELECT
 portal,
 partner,
 location_quality
FROM
 table01
GROUP BY
 portal,
 partner
WHERE
 (location_quality * 0.9) > 50

答案 2 :(得分:0)

我提出了与Roger相似的解决方案,

SELECT DISTINCT partner, portal from (
    SELECT partner, portal, sum(case when location_quality > 50 then 1 else null end) as cnt_greater_50, CAST(count(*) AS FLOAT) as total_cnt
    FROM tb
    GROUP BY partner, portal
) WHERE cnt_greater_50/total_cnt > 0.9

还有更好的主意吗?感谢