如何将此SQL表聚合到另一个表中?

时间:2014-06-30 21:44:06

标签: sql sql-server select

如果我有以下数据表:

COLUMN 1    COLUMN2
Country1    NULL
Country1    0
Country1    NULL
Country1    0
Country1    NULL
Country1    0
Country1    NULL
Country1    18
Country1    NULL
Country1    12
Country1    NULL
Country1    0
Country1    NULL
Country1    0
Country1    NULL
Country2    0
Country2    NULL
Country2    7
Country2    NULL
Country2    0
Country2    NULL
Country2    0
Country2    NULL
Country2    0

忽略第二列为NULL的行,如何从中获取以下值:

Country1有7个值,其中5个为零,1个为18,1个为12。 Country2有5个值,其中4个为零,1个为7

如何获得一个看起来像这样的表?

COUNTRY VALUE   PERCENT
Country1    0   71.43 (i.e. 5/7)
Country1    18  14.29 (i.e. 1/7)
Country1    12  14.29 (i.e. 1/7)
Country2    0   80 (i.e. 4/5)
Country2    7   20 (i.e. 1/5)

2 个答案:

答案 0 :(得分:1)

您可以使用简单的聚合和窗口函数来执行此操作:

select country, value,
       cast(count(*) as float) / sum(count(value)) over (partition by country) as ratio
from table t
group by country, value;

这将第三列作为比率。您可以通过各种方式将其格式化为百分比,例如使用str()

答案 1 :(得分:0)

以下是可以帮助您的查询结构:

select t1.column1, t1.column2, t1.cnt*100.0/t2.totalcnt
from
(
select column1, column2, count(*) as cnt
from table
where column2 is not null
group by column1, column2
) as t1
inner join
(
select column1, count(*) as totalcnt
from table
where column2 is not null
group by column1
) as t2
on t1.column1=t2.column1