【问题标题】:Transact-SQL Count using a subselect statement filtering on a variable from top selectTransact-SQL 计数使用子选择语句从顶部选择过滤变量
【发布时间】:2015-02-27 19:11:50
【问题描述】:

我正在尝试将与特定用户关联的记录帐户与有关该用户的其他信息包含在同一行中。比如:

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

...

这样的事情可能吗?

【问题讨论】:

    标签: sql tsql select count subquery


    【解决方案1】:

    使用列名代替别名

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

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

    【讨论】:

    • 为 au.Username 选择的值是否与在 subselect 语句之外选择的值相同?
    • 这行得通,谢谢。将 count() 放入选择中就是这样做的。
    【解决方案2】:

    count()放在select里面:

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

    关联也不能使用列别名。它需要使用as之前的部分。别名超出了子查询的范围。

    【讨论】:

      【解决方案3】:
      select au.UserName as UsersName, count(sg.Id)
        from au 
        join sg 
          on sg.Username = au.UserName
       group by au.UserName 
      

      【讨论】:

        猜你喜欢
        • 2016-08-28
        • 1970-01-01
        • 2022-01-13
        • 2023-03-30
        • 1970-01-01
        • 2012-05-05
        • 2015-03-02
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多