6

我有一个看起来像这样的表:

    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 占总数的百分比。

我可以用这个查询得到 2s 的数量

    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 

如何获得总数并计算百分比?

谢谢!

4

1 回答 1

3
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;

结果:

在此处输入图像描述

于 2012-04-27T19:17:20.287 回答