根据特定条件SQL计算每个组的百分比贡献

时间:2018-05-29 09:31:54

标签: mysql sql

我想计算"数量"的百分比。 2组的贡献,第1组其中"客户ID"出现不止一次和第2组,其中"客户ID"是一次。例如:

|ID | OrderID   |Quantity
|---|--------   |-----
|1  |10248      |12
|2  |10248      |10 
|3  |10248      |5 
|4  |10249      |9
|5  |10249      |40
|6  |10250      |10

- - - - - - - - 进

OrderID |Quantity
10248   |27
10249   |49
10250   |10

-----最终进入-----

Group    % tot Quantity
1         12%   <--- Just OrderID 10250 since it has only 1 order
2         88%

4 个答案:

答案 0 :(得分:1)

select
   100.0 * sum(case when cnt = 1  then sumQty else 0 end) / sum(sumQty) as "single Order"
  ,100.0 * sum(case when cnt <> 1 then sumQty else 0 end) / sum(sumQty) as "multiple Orders"
from
 (
    select 
       OrderID
      ,sum(Quantity) as sumQty
      ,count(*) as cnt
    from myTable
    group by OrderId
 ) as dt

答案 1 :(得分:0)

也许这会有所帮助。否则有任何不妥之处请告诉我。

select a.OrderID,a.grp, Cast(Cast(a.Quantity*100 as decimal(18,2)) as varchar(100)) + ' %' as Percentage from (
select OrderID as OrderID,count(OrderID) as grp,Sum(Quantity) as Quantity  from myTable
group by OrderID
) as a

答案 2 :(得分:0)

以前的答案不起作用它回复33% 这项工作很好:

select 100.0 * sum(case when cnt = 1  then sumQty else 0 end) / sum(sumQty) as 'single Order'
,100.0 * sum(case when cnt <> 1 then sumQty else 0 end) / sum(sumQty) as 'multiple Order'
from
 (
select 
   OrderID
  ,sum(Quantity) as sumQty -- not needed for the final result
  ,count(*) as cnt
from _ds_test_ac
group by OrderId
) as dt

如果您想要两行,您可以这样做:

select cnt = 1 as 'IS Single',   100.0 * sum(sumQty) / tot as 'percent'
from
 (
    select 
       OrderID
      ,sum(Quantity) as sumQty -- not needed for the final result
      ,count(*) as cnt
    from _ds_test_ac
    group by OrderId
 ) as dt join 
 (
 select sum(Quantity) as tot
    from _ds_test_ac
 ) dtot 
group by 1

答案 3 :(得分:0)

其他答案将值放入一行,但OP要求两行。如果这很重要:

select (case when cnt = 1 then 1 else 2 end) as grp,
       qty / totQty as ratio
from (select OrderID, sum(Quantity) as Qty, count(*) as cnt
      from myTable
      group by OrderId
     ) o cross join
     (select sum(Quantity) as totQty from myTable) x
group by (case when cnt = 1 then 1 else 2 end);