计算具有...的行数 SQL
Count number of rows with having... SQL
我必须计算 UserId 是否被列出一次或多次,如果一次将 +1 设置为 "new users",否则将“+1”设置为 "returning users"。
我做过吗:
select
Count(distinct [UserId]) as 'Unique users'
from [TelemetryData]
where [DiscountId] = '8CAEA860-6766-43E2-9280-27AFE7FDF82E' and [EventName] = 'DiscountClick'
/* returning */
select
count(Id) as 'Returning users'
from [TelemetryData]
where [DiscountId] = '8CAEA860-6766-43E2-9280-27AFE7FDF82E' and [EventName] = 'DiscountClick'
group by [UserId]
having count(Id) > 1
/* returning */
select
count(*) as 'New users'
from [TelemetryData]
where [DiscountId] = '8CAEA860-6766-43E2-9280-27AFE7FDF82E' and [EventName] = 'DiscountClick'
group by [UserId]
having count(*) = 1
我需要像第一个查询一样计算 "returning" 和 "new" 用户查询中的总行数。怎么做?
您可以使用两个级别的聚合来执行此操作。计算 UserId
级别的计数,然后使用该信息获得所需的计数:
select sum(case when cnt > 1 then 1 else 0 end) as ReturningUsers,
sum(case when cnt = 1 then 1 else 0 end) as NewUsers
from (select UserId, count(*) as cnt
from [TelemetryData]
where [DiscountId] = '8CAEA860-6766-43E2-9280-27AFE7FDF82E' and [EventName] = 'DiscountClick'
group by UserId
) u
我必须计算 UserId 是否被列出一次或多次,如果一次将 +1 设置为 "new users",否则将“+1”设置为 "returning users"。
我做过吗:
select
Count(distinct [UserId]) as 'Unique users'
from [TelemetryData]
where [DiscountId] = '8CAEA860-6766-43E2-9280-27AFE7FDF82E' and [EventName] = 'DiscountClick'
/* returning */
select
count(Id) as 'Returning users'
from [TelemetryData]
where [DiscountId] = '8CAEA860-6766-43E2-9280-27AFE7FDF82E' and [EventName] = 'DiscountClick'
group by [UserId]
having count(Id) > 1
/* returning */
select
count(*) as 'New users'
from [TelemetryData]
where [DiscountId] = '8CAEA860-6766-43E2-9280-27AFE7FDF82E' and [EventName] = 'DiscountClick'
group by [UserId]
having count(*) = 1
我需要像第一个查询一样计算 "returning" 和 "new" 用户查询中的总行数。怎么做?
您可以使用两个级别的聚合来执行此操作。计算 UserId
级别的计数,然后使用该信息获得所需的计数:
select sum(case when cnt > 1 then 1 else 0 end) as ReturningUsers,
sum(case when cnt = 1 then 1 else 0 end) as NewUsers
from (select UserId, count(*) as cnt
from [TelemetryData]
where [DiscountId] = '8CAEA860-6766-43E2-9280-27AFE7FDF82E' and [EventName] = 'DiscountClick'
group by UserId
) u