SQL子查询计算频率超过平均频率

时间:2013-05-27 14:57:47

标签: sql sql-server

我想创建一个代表某些商店性能的图表。 x轴将代表商店的总收入超过所有商店的平均收入。

y轴将代表平均频率特定商店的客户此商店超过平均频率所有客户访问全部商店。

这就是我的尝试:

select 
distinct [Order].shop_id 
, SUM(total) /((select AVG(o.shopTotal) 
                            from 
                            (
                            select 
                                    distinct shop_id , SUM(total) as shopTotal 
                                    from [Order] 
                                    group by shop_id
                            )o)*0.1) as revPerAvgRev

,COUNT(distinct orderno) /((select AVG(orders) 
                            from 
                            (
                            select 
                                    distinct shop_id , room, COUNT(distinct orderno) as orders 
                                    from [Order] 
                                    group by shop_id , room
                            )o)*0.1) as freqPerAvgFreq
from [Order] 
group by [order].shop_id
order by revPerAvgRev desc

select distinct shop_id ,room , count(distinct orderno)
from [Order] 
group by shop_id , room

我相信顾客访问商店的平均频率是可以的。 但我无法计算每个客户访问 商店的平均频率。

注意:每个客户只访问一家商店。

1 个答案:

答案 0 :(得分:1)

要完全按照自己的意愿行事有点困难。您要求频率,但代码示例显示收入。您可以使用窗口函数计算总收入来获得收入比例:

select shop_id, shopTotal,
       cast(shopTotal as float)/ sum(shopTotal) over () as Revenue,ProportionOfTotal,
       numvisits,
       cast(numvisits as float) / sum(numvisits) over () as VisitsProportionOfTotal
from (select shop_id , SUM(total) as shopTotal, count(*) as numvisits
      from [Order] 
      group by shop_id
     ) s