SQL中使用分组依据的百分比列

时间:2019-02-14 15:03:51

标签: sql sql-server

我有一个由数据库,表,变量,值和频率计数组成的表。我想对此进行查询,并创建一个[Percent]列,该列将是变量级别的总频率。

我已经设法加入了总数,但是计算百分比似乎没有用。每个百分比值我都会得到0。

select t1.[database], 
       t1.[table], 
       t1.[variable],
       t1.[value],
       t1.[frequency],
       t2.[vartotal],
       ([frequency]) / t2.vartotal *100 as [Percent]
from TestDB.dbo.Meta t1
join (select [database], [table_name], [variable], sum(frequency) as vartotal
    from TestDB.dbo.Meta
    group by [database], 
             [table], 
             [variable]) t2
on t1.[database]=t2.[database] and 
   t1.[table]=t2.[table] and 
   t1.[variable]=t2.[variable]
group by t1.[database], t1.[table_name], t1.variable, 
t1.[value], t1.[frequency], t2.[vartotal]

为什么所有百分比计算都返回零?

2 个答案:

答案 0 :(得分:2)

SQL Server执行整数除法,因此1/2 = 0,而不是0.5。我通常只需乘以1.0即可解决此问题:

  ([frequency] * 100.0 / t2.vartotal) as [Percent]

也就是说,您可以使用窗口函数进行此计算:

select . . .,
      sum(frequency) over (partition by database, table, variable) as vartotal,
       ([frequency] * 100.0 / sum(frequency) over (partition by database, table, variable) ) as [Percent]
from TestDB.dbo.Meta t1;

这比您的查询简单得多,并且应该具有更好的性能。

答案 1 :(得分:1)

可能是关于什么数据类型频率的问题。请尝试以下操作: 也可能想添加一些额外的父母,以确保操作顺序。

select t1.[database], 
       t1.[table], 
       t1.[variable],
       t1.[value],
       t1.[frequency],
       t2.[vartotal],
       ((TRY_CONVERT(FLOAT, [frequency])) / TRY_CONVERT(FLOAT, t2.vartotal)) * 100 as [Percent]
from TestDB.dbo.Meta t1
join (select [database], [table_name], [variable], sum(frequency) as vartotal
    from TestDB.dbo.Meta
    group by [database], 
             [table], 
             [variable]) t2
on t1.[database]=t2.[database] and 
   t1.[table]=t2.[table] and 
   t1.[variable]=t2.[variable]
group by t1.[database], t1.[table_name], t1.variable, 
t1.[value], t1.[frequency], t2.[vartotal]