1

I have to count if UserId is listed one or more times and if one put +1 to "new users" else "+1" to "returning users".

Have I have done:

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 

I need count total numer of rows in "returning" and "new" users query like in first query. How to do it?

1
  • This looks like SQL Server code so I added that tag. Commented Oct 19, 2016 at 10:49

1 Answer 1

3

You can do this with two levels of aggregation. Calculate the count at the UserId level, then use that information to get the counts you want:

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
Sign up to request clarification or add additional context in comments.

4 Comments

its not working 'cnt' not found. 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] )
@Nerf use whole query. with u in the end
Oh right. What is 'u'? I thought it was misstake and removed it ;D
Now how I can insert this select to another select? I'm getting error with "exists"...

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.