如何在连接结果中包含计数?

时间:2015-09-16 23:56:20

标签: sql ado

我正在使用VBA使用ADO构建SQL查询。我有一个连接查询,如下所示:

select user.id,user.city,action.id
from user
left join
action
on
user.id=action.userID

我想添加一个给我user.city计数的列,以便我的结果看起来像:

+---------+-----------+-----------+-----------+
| user.id | user.city | cityCount | action.id |
+---------+-----------+-----------+-----------+
|       1 | DMZ       |         3 |         9 |
|       1 | DMZ       |         3 |        44 |
|       2 | KLF       |         1 |     23523 |
|       3 | DMZ       |         3 |         3 |
+---------+-----------+-----------+-----------+

我想也许我必须收集此查询的汇总并将其加入原始查询中,如下所示:

select user.id,user.city,cc.cityCount,action.id,action.action
from user
left join
action
on
user.id=action.userID
left join
(select city,count(city) as cityCount from 
 (select user.id,user.city,action.id,action.action
  from user
  left join
  action
  on
  user.id=action.userID) 
 group by city) cc
on
user.city=cc.city

是否有更直接的方法来获得此计数而无需两次写出(并执行)相同的查询?

1 个答案:

答案 0 :(得分:0)

另一种方法是使用相关子查询:

select u.id, u.city, a.id,
       (select count(*)
        from user u2 join
             action a2
             on u2.id = a2.id
        where u2.city = u.city
       ) as cityCount
from user u left join
     action a
     on u.id = a.userID;