SQL中的聚合以计算总和和百分比

时间:2017-10-22 09:18:53

标签: sql metabase

我的数据库中有这些数据,显示有多少用户被邀请和参与,我想计算以下内容:

1-总邀请函(计数总和) 2-参与(允许的总和,to_be_paid,already_paid) 3-回复(允许的总和,to_be_paid,already_paid,user_declined,user_willing)
4-无回复(已过期,已提供)
5-回复率(回复/总计* 100) 6-参与率(参与/总计* 100)

Table view

我希望能够得到这样的结果:

Final result

1 个答案:

答案 0 :(得分:0)

我认为这可以帮助你。我改变了这一点并测试它是正确的

  declare @Responded int
  declare @Total int
  declare @Participated int

  set @Total=(select SUM([count]) as Total from [dbo].[tb1])

  set @Participated=(select SUM([count]) as Participated  from [dbo].[tb1]
  where Status in('allowed', 'to_be_paid', 'already_paid'))

  set @Responded=( select SUM([count]) as Responded   from [dbo].[tb1]
  where Status in('allowed', 'to_be_paid', 'already_paid', 'user_declined', 'user_willing'))
(SELECT  [Status]
      ,cast([count] as DECIMAL(38,0))
  FROM [Identity].[dbo].[tb1]
  )
  union 
  (
  select 'Total',cast(@Total as DECIMAL(38,0))
  )
  union 
  (
  select 'Participated',cast(@Participated as DECIMAL(38,0))
  )
  union 
  (
  select 'Responded',cast(@Responded as DECIMAL(38,0))
  )
  union 
  (
  select 'No response',cast(SUM([count]) as DECIMAL(38,0)) as [count] from [dbo].[tb1]
  where Status in('expired', 'offered')
  )
  union(
  select 'Response rate', cast(((100.0 * @Responded)/ @Total)as DECIMAL(38,0)) as [count]
  )
  union(
  select 'Participation rate',cast(((100.0 * @Participated)/ @Total)as DECIMAL(38,0))as [count]
  )

Result