3

我在一个健身俱乐部的 SQL Server 数据库中有一个客户列表。客户列出了他们加入的日期和他们续订的次数我希望能够计算出续订客户的百分比。关于如何做到这一点的任何想法?谢谢。

4

2 回答 2

5

如果有一个表subscriptions,每个用户只有一行,则会更新一点isrenewed

 SELECT 
    SUM(SIGN(isrenewed)) * 100 / COUNT(*) 
    AS Percentage
    FROM subscriptions

输出

 Percentage
 ---------------
 66,666666

如果要对表达式进行四舍五入,可以将其转换为 int

 SELECT 
    CAST(
      SUM(SIGN(isrenewed)) * 100 / COUNT(*) 
      AS int)
    AS Percentage
    FROM subscriptions

输出

 Percentage
 ---------------
 66

如果您有一个subscriptions包含用户特定列的表,userid其中有两行意味着订阅已更新:

SELECT 
  (SELECT TOP 1 COUNT(*) OVER() 
    FROM subscriptions
    GROUP BY userid
    having COUNT(*) > 1) 
  * 100 / COUNT(*) AS Percentage
  FROM subscriptions
于 2012-10-25T04:54:25.040 回答
1

这是你想要的

Declare @t table(Id Int Identity,CustomerName Varchar(50),DOJ Datetime,IsRenewed bit)
Insert Into @t Values('Name1','1/1/2012',1),('Name2','10/1/2012',1),('Name3','10/2/2012',0)

Select PercentageCustomerRenewed = 
Cast((Count(*) * 100) / (Select Count(*) From @t ) AS Numeric(10,2))  
From @t 
where IsRenewed = 1

结果

PercentageCustomerRenewed
66.00
于 2012-10-25T04:50:51.657 回答