2012-07-18 48 views
1

我有一個報告,其中我計算了各個國家和子區域的報價。現在我有一些國家爲空的引號。SQL中的稱量因子

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字段是空白的。因此,我被要求獲得歐洲,中東和非洲地區的報價,並使用基於報價當前價差的權重因子在德國,西班牙,法國和其他歐洲,中東和非洲地區國家分發報價,然後將報價添加到該地區的其他國家如歐洲,中東和非洲。

那麼目前我完全困惑於如何做到這一點?有任何想法嗎 ?

幫助?有人?

第1步 - 獲取歐洲,中東和非洲地區所有國家的當前權重因子。在SQL?

第2步 - 獲取沒有分配給歐洲,中東和非洲地區的報價的報價。在SQL?

第3步 - 根據稱量因子,引用報價並向每個國家添加x個報價。在SQL?

+0

引號添加到數字必須是整數 – 2012-07-18 15:29:51

回答

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

要獲得的加權因子做:

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