0

我想计算 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

4 回答 4

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
于 2018-05-29T09:38:25.927 回答
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
于 2018-05-29T09:58:55.493 回答
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
于 2018-05-29T10:09:28.267 回答
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);
于 2018-05-29T11:06:18.070 回答