How To Do Percent/Total in SQL?

前端 未结 4 1569
梦如初夏
梦如初夏 2021-01-07 17:12

I have an typical CUSTOMER/ORDERS set of tables and I want to display the total percentage of sales a particular customer is responsible for. I can get the

4条回答
  •  迷失自我
    2021-01-07 17:21

    MySQL:

    SELECT ROUND(
      100.0 * (
          SUM(IF(cust_id = 541, 1, 0)) / COUNT(order_id)
      ), 1) AS percent_total
    FROM orders;
    

    Edit

    I guess it helps if I would have noticed the postgres tag. I thought it was a MySQL question.

    PostgreSQL:

    SELECT ROUND(
      100.0 * (
          SUM(CASE WHEN cust_id = 541 THEN 1 ELSE 0 END) / COUNT(order_id)
      ), 1) AS percent_total
    FROM orders;
    

    P.S. My PostgreSQL is rusty, so if the MySQL query works on PostgreSQL I'd like to know :)

    Edit 2

    I can't stress enough to be wary of the count(*) suggestion below. You generally want to avoid this with PostgreSQL.

提交回复
热议问题