SQL中的称量因子

时间:2012-07-18 15:23:07

标签: sql sql-server

我有一份报告,其中我统计了各个国家/地区和SubRegions的报价。现在我有一些引号,其中Country为null。

Table 
Quote Number | Country | Subregion | Quote Count 
12233        | Germany | EMEA      | 100 
2223         | Blank   | EMEA      | 3333
3444         | France  | EMEA      | 200
455454       | Spain   | EMEA      | 300

总票数无空国家说等于1000,其中10%与德国等有关。因此德国加权因子为0.1。

总的来说,我有3333个引号,其中country字段为空。因此,我被要求获取EMEA的报价,并使用基于报价当前价差的加权因子在德国,西班牙,法国和其他EMEA国家/地区之间分配报价,然后将报价添加到该地区的其他国家,如EMEA。

所以目前我对如何做到完全感到困惑?有什么想法吗?

帮助?有人吗?

第1步 - 获取EMEA所有国家/地区的当前加权因子。在sql?

第2步 - 获取没有为EMEA指定国家/地区的报价的报价计数。在sql?

步骤3 - 根据称量因子获取报价并向每个国家/地区添加x引号。在sql?

2 个答案:

答案 0 :(得分:2)

根据样本中的数据:

WITH    Factors
      AS ( SELECT   Country ,
                    SUM([Quote Count])
                    / CAST(( SELECT SUM([Quote Count])
                             FROM   dbo.quotes
                             WHERE  Region = q.Region
                                    AND Country IS NOT NULL
                           ) AS FLOAT) AS WeightingFactor ,
                    q.Region
           FROM     dbo.quotes q
           WHERE    country IS NOT NULL
           GROUP BY q.Country ,
                    q.Region
         )
SELECT  q.country ,
        ( SELECT    SUM([quote count])
          FROM      dbo.quotes
          WHERE     Country IS NULL
                    AND Region = q.Region
        ) * f.WeightingFactor + SUM(q.[Quote Count]) AS [Quote Count]
FROM    dbo.quotes q
        JOIN Factors f ON q.Country = f.Country
                          AND q.Region = f.Region
WHERE   q.Country IS NOT NULL
GROUP BY q.Country ,
        q.Region ,
        WeightingFactor

答案 1 :(得分:1)

要获得加权因子,请执行以下操作:

select country, quotecount,
       quotecount*1.0/sum(quotecount) over (partition by null) as allocp
from t
where country <> 'Blank'

要重新添加这些内容,请加入总计:

select t.country, t.region, t.quotecount,
       (t.quotecount + allocp*b.BlankBQ) as AllocatedQC
from (select country, quotecount,
             quotecount*1.0/sum(quotecount) over (partition by region) as allocp
      from t
      where country <> 'Blank'
     ) t join
     (select sum(QuoteCount) as BlankBQ
      from t
      where country = 'Blank'
      group by region
     ) b
     on t.region = b.region