增长率最高

时间:2017-09-11 07:08:50

标签: sql postgresql

我正在使用Postgres 9.6和pgadmin 4。

我的问题如下:

2014年至2015年哪个部门的增长率最高?多少钱?

这是两个表之间的连接

表1:case_data_order

  • create_timestamp-(timestamp)如下所示:2014-01-01 10:12:20
  • purchase_amount-(bigint)购买金额
  • id - (数字) - 单次购买的ID
  • merchant_id - 与以下相同。

表2:case_data_merchant

  • merchant_category(text) - 这是差异细分
  • 的地方
  • merchant_id-(bigint)购买商品的ID

我曾多次尝试,但我不知道该怎么做。

select merchant_category ((purchase_amount_2014-purhase_amount_2015)/purchase_amount_2014*100) 
from (
    select sum(purchase_amount) as purchase_amount_2015 
    from case_data_order 
       natural join case_data_merchant 
    where create_timestamp between '2014-01-01' and '2014-12-31'
  group by merchant_category) as data_2015

自然加入 (选择sum(purchase_amount)作为purchase_amount_2014         来自case_data_order            自然连接case_data_merchant         其中create_timestamp在'2015-01-01'和'2015-12-31之间     group by merchant_category)as data_2014;

1 个答案:

答案 0 :(得分:0)

您可以在2014年,2015年首先为每个商家类别选择购买数据。然后加入这些数据并使用RANK功能获得每个类别的排名。

WITH ranking_data 
     AS (
        SELECT q1.merchant_category, 
               q1.purhase_amount AS  purchase_amount_2014,
               q2.purchase_amount AS  purchase_amount_2015,
               RANK() OVER (ORDER BY q2.purchase_amount - q1.purhase_amount DESC) AS purchase_rank 
         FROM   (SELECT d.merchant_category, 
                        Sum(d1.purchase_amount) AS purchaseamount 
                 FROM   case_data_order d1 
                        INNER JOIN case_data_merchant d2 
                                ON d1.merchant_id = d2.merchant_id 
                 WHERE  d1.create_timestamp BETWEEN 
                        '2014-01-01' AND '2014-12-31' 
                 GROUP  BY d2.merchant_category) q1 
                INNER JOIN (SELECT d.merchant_category, 
                                   Sum(d1.purchase_amount) AS purchaseamount 
                            FROM   case_data_order d1 
                                   INNER JOIN case_data_merchant d2 
                                           ON d1.merchant_id = d2.merchant_id 
                            WHERE  d1.create_timestamp BETWEEN 
                                   '2015-01-01' AND '2015-12-31' 
                            GROUP  BY d2.merchant_category) q2 
                        ON q1.merchant_category = q2.merchant_category
        ) 
SELECT 
    merchant_category, 
    CASE 
        WHEN purchase_amount_2015 = 0 THEN 0
        ELSE ((purchase_amount_2015 - purchase_amount_2014) / purchase_amount_2015 * 100 )
    END AS percentage_growth
FROM   ranking_data 
WHERE  purchase_rank = 1;