【问题标题】:Calculate percentage between two tables with group by -SQL (Impala)使用 group by -SQL (Impala) 计算两个表之间的百分比
【发布时间】:2017-11-02 18:28:28
【问题描述】:

我正在开发 Impala (Cloudera),我有两个表,客户和安排。客户表有以下列:

customercrs | customertype| 
------------+-------------+
 1000       | NP          |  
 100000     | NP          |   
 100001     | NP          |  
 100002     | GROUP       |  
 100023     | GROUP       |
 100024     | INDIRECT    |

安排表:

customercrs | arrangementid| 
------------+--------------+
 1000       | 11000000361  |  
 100000     | 11000000370  |  
 100000     | 11000000434  |
 100000     | 11000000426  |
 100001     | 11000000418  | 
 100001     | 11000000400  |
 100001     | 11000000396  |
 100001     | 11000000388  |
 100002     | 11000000591  |  
 100002     | 11000000582  |
 100023     | 11000000574  |
 100024     | 11000000566  |
 100024     | 11000000558  |

我想计算每种客户类型的安排百分比。比如:

customertype | percentage  |
-------------+-------------+
 NP          | 62%         |
 GROUP       | 23%         |
 INDIRECT    | 15%         |

我尝试了以下 sql 查询,但没有成功。有什么想法吗?

select customertype, count(*)/(select count(*) from arrangements)
from customers as a, arrangements_sample as b
where a.customercrs = b.customercrs
group by a.customertype

谢谢!!!

【问题讨论】:

  • 查询有什么问题?
  • AnalysisException: 选择列表中不支持子查询这是我得到的异常

标签: sql impala


【解决方案1】:

我会将窗口函数与显式 JOIN 一起使用,但是,您的解决方案似乎很好(对于 Impala 以外的其他 DBMS)

select customertype, 
       (count(*) * 100) / sum(count(*)) over () percentage
from customers as a
join arrangements_sample as b on a.customercrs = b.customercrs
group by a.customertype

【讨论】:

  • 感谢您的快速回答,但似乎不起作用。我只得到每个类别的计数,而不是百分比。
  • @VickyK 是的,我只是忘记了SUM。现在可以试试吗?
【解决方案2】:

尝试加入子选择,我使用 max 作为组函数,但 min 或 avg 也可以...

select customertype, count(*)/max(c.total)
from customers as a, arrangements_sample as b, (select count(*) as total from 
arrangements) as c
where a.customercrs = b.customercrs
group by a.customertype

【讨论】:

    【解决方案3】:

    您需要每种客户类型参与安排的总数。所以请尝试以下查询。

    选择 main.customertype,cast((cast(main.participation as decimal(10,2))/main.total)*100 as decimal(10,2)) 作为参与 从(选择客户类型,COUNT(1) 作为参与,(从安排中选择 COUNT(1))作为总数从安排 a 在 b.customercrs = a.customercrs 上内部加入客户 b 按 b.customertype 分组)为主

    【讨论】:

      猜你喜欢
      • 2013-05-31
      • 2016-07-02
      • 2011-09-06
      • 2019-02-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多