2

I'm trying to include account of records associated with a particular user in the same row as other information about the user. Something like:

select
    au.UserName as UsersName,
    Count(
        select sg.Id from sg
        where sg.Username = UsersName
     )

...

Is something like this possible?

PLan
  • 133
  • 7

3 Answers3

1

Put the count() inside the select:

select au.UserName as UsersName,
       (select count(sg.Id)
        from sg
        where sg.Username = au.UserName
       )

The correlation also cannot use the column alias. It needs to use the part before the as. The alias is outside the scope of the subquery.

Gordon Linoff
  • 1,242,037
  • 58
  • 646
  • 786
0

Use column name instead of alias name

select
    au.UserName as UsersName,
    (
        select count(sg.Id) from sg
        where sg.Username = au.UserName
     ) as Count
...

DEMO http://sqlfiddle.com/#!3/8b62d/10

HaveNoDisplayName
  • 8,291
  • 106
  • 37
  • 47
  • Will the value selected for au.Username be the same as the one chosen outside of the subselect statement? – PLan Dec 31 '14 at 19:24
  • This works, thanks. Putting count() inside the select is what did it. – PLan Dec 31 '14 at 19:44
0
select au.UserName as UsersName, count(sg.Id)
  from au 
  join sg 
    on sg.Username = au.UserName
 group by au.UserName 
paparazzo
  • 44,497
  • 23
  • 105
  • 176