2012-04-27 91 views
5

我有一個表,看起來像這樣:如何透視和計算t-sql中的百分比?

DECLARE @myTable TABLE (country varchar(max), code int) 
    INSERT @myTable 
    SELECT 'A', 1 UNION ALL 
    SELECT 'A', 1 UNION ALL 
    SELECT 'A', 1 UNION ALL 
    SELECT 'A', 2 UNION ALL 
    SELECT 'A', 2 UNION ALL 
    SELECT 'B', 1 UNION ALL 
    SELECT 'B', 1 UNION ALL 
    SELECT 'B', 1 UNION ALL 
    SELECT 'B', 1 UNION ALL 
    SELECT 'B', 2 UNION ALL 
    SELECT 'C', 1 UNION ALL 
    SELECT 'C', 1 UNION ALL 
    SELECT 'C', 1 ; 

欲樞軸轉動而離開A/B/C,然後計數2秒的數量和具有總的2的百分比。

我可以得到2秒的數量與此查詢

DECLARE @mySecondTable TABLE (country varchar(max), code int); 
    INSERT @mySecondTable 
     SELECT * FROM @myTable 
     WHERE code=2; 

    SELECT [A], [B], [C] 
    FROM 
    (SELECT Country, code 
     FROM @mySecondTable) AS source 
    PIVOT 
    (
     COUNT(code) 
     FOR Country IN ([A], [B], [C])) AS pvt; 

但我真的希望它看起來是這樣的:

A   B   C 
    2 (40.0%) 1 (20.0%) 0 

如何獲得總計並計算百分比?

謝謝!

+0

你接受不返回正確的結果:( – 2012-04-27 20:18:05

+0

嗨約翰的解決方案,我被鎖了由於某種原因,這裏是我的評論Hi Lamak,那。使用錯誤的總數來計算百分比,因爲AI需要總數爲5,所以總數的百分比是2 = 2/5 = 40%。對於B,它將是1/5 = 20% – user918967 2012-04-27 21:29:45

回答

2
DECLARE @myTable TABLE (country varchar(max), code int) 
    INSERT @myTable 
    SELECT 'A', 1 UNION ALL 
    SELECT 'A', 1 UNION ALL 
    SELECT 'A', 1 UNION ALL 
    SELECT 'A', 2 UNION ALL 
    SELECT 'A', 2 UNION ALL 
    SELECT 'B', 1 UNION ALL 
    SELECT 'B', 1 UNION ALL 
    SELECT 'B', 1 UNION ALL 
    SELECT 'B', 1 UNION ALL 
    SELECT 'B', 2 UNION ALL 
    SELECT 'C', 1 UNION ALL 
    SELECT 'C', 1 UNION ALL 
    SELECT 'C', 1 ; 

    DECLARE @mySecondTable TABLE (country varchar(10), pct varchar(20), code int); 
    INSERT @mySecondTable 
     SELECT country 
     , pct=cast(count(*)over(partition by country,code) as varchar(10)) 
      +' ('+cast(100* 
       cast(count(*)over(partition by country,code)as decimal(3,2)) 
       /CAST(count(*)over(partition by country) as decimal(3,2)) as varchar(10)) 
      +'%)' 
     , code 
     FROM @myTable 

    SELECT [A], [B], [C] 
    FROM 
    (SELECT Country, pct 
     FROM @mySecondTable 
     WHERE code=2 
    ) AS source 
    PIVOT 
    (
     MAX(pct) 
     FOR Country IN ([A], [B], [C])) AS pvt; 

結果:

enter image description here