In Postgres, how do I COUNT and WHERE in the same query, then do math on result?

喜夏-厌秋 提交于 2020-01-06 04:37:25

问题


I have a large DB of SALES_ORDERS, that I need to determine the % each SELLING_AGENT had in the ORDER.

Learning postgresql, and this is just a sample, of ~500k rows of data. Each ORDER# could be composed of dozens of SALE_ITEMs (but only composed of 'SALE_ITEM_1' and 'SALE_ITEM_2').

I thought I could try doing a SUM SELECT something like this:

    SELECT (SUM(sale_item_1)+sum(sale_item_2)) as total_person_sale
    FROM SALES_ORDER
    WHERE orderNumber LIKE orderNumber
    GROUP by SELLING_AGENT

But clearly I'm not grasping the WHERE statement use to count similar

The hope is to fill out the final column, like this: selling agent:

    selling agent:  Order#  Sale_item_1 Sale_item_2 %_of_TOTAL_order
    jim              abc    $1.00       $2.00       14.29%
    steve            abc    $3.00       $4.00       33.33%
    carl             abc    $5.00       $6.00       52.38%
    carl             def    $7.00       $8.00       31.25%
    steve            def    $9.00       $9.00       37.50%
    jim              def    $8.00       $7.00       31.25%
    steve            ghi    $6.00       $5.00       61.11%
    patty            ghi    $4.00       $3.00       38.89%

回答1:


Something like this:

SELECT 
  s.*, 
  ROUND (
  100.00 * (s.sale_item_1 + s.sale_item_2) /
  (SELECT 
     SUM(sale_item_1 + sale_item_2)
     FROM sales_db 
     WHERE orderNumber = s.orderNumber), 2) percentage
FROM sales_db s;

See the demo




回答2:


You're trying to do something that is somewhat advanced. I'll give you two options:

SELECT selling_agent, orderNumber,
    sum(sale_item_1) as sale_item_1,
    sum(sale_item_2) as sale_item_2,
    (sum(sale_item_1) + sum(sale_item_2)) * 100.00 /
        sum(sum(sale_item_1) + sum(sale_item_2)) over (partition by orderNumber) as orderPercentage
FROM sales_db
--WHERE orderNumber LIKE orderNumber /* I'm not sure what this is about */
GROUP by orderNumber, selling_agent
ORDER BY orderNumber, selling_agent

This is the old way via a subquery:

SELECT selling_agent, orderNumber,
    sum(sale_item_1) as sale_item_1,
    sum(sale_item_2) as sale_item_2,
    (sum(sale_item_1) + sum(sale_item_2)) * 100.00 /
        (
        select sum(sale_item_1 + sale_item_2)
        from sales_db s2
        where s2.orderNumber = s.orderNumber
        )
FROM sales_db s
--WHERE orderNumber LIKE orderNumber
GROUP by orderNumber, selling_agent
ORDER BY orderNumber, selling_agent

By the way, if each selling agent is only represented once per order number this could be simplified a bit.



来源:https://stackoverflow.com/questions/54055923/in-postgres-how-do-i-count-and-where-in-the-same-query-then-do-math-on-result

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!