如何优化查询 - 使用视图提取计数信息

时间:2015-05-13 09:58:20

标签: sql sql-server

如何构建以下查询以同时运行多个数据库。

要计算db中活动用户的总数,我目前必须一次运行一个数据库的查询。

我可以动态运行某种foreach函数吗?

with data as
(select p.CoNum CoNum, p.LastName, p.Name,co.name Company, liGender.Description as Gender, liEth.Description as EthnicGroup,Isnull(Limed.Description,'Not Specified') FinancialAid,
  vwPTU.[UserP Type] as UserPType

from UsersP p
  left outer join ListItem liGender on liGender.Id = p.Gender
  left outer join ListItem liEth on liEth.Id = p.EthnicGroup
  left outer join ListItem limed on limed.Id = p.FinancialAidId
  inner join UserPOrgNodeAssociation pona on P.Id = pona.UserPId
  inner join CoAssociation coda on pona.CoNodeDescAssociationId = coda.Id
  inner join Company co on coda.companyid=co.id
  left outer join [dbo].[vw_XUserUniqueView] vwPTU on p.Id = vwPTU.Id
    and vwPTU.[ValidToDate] > '2015/12/31 23:59 PM'

where vwPTU.[User Type] is not null

)
select Company, count(distinct CoNum) as Total
from data
group by company

1 个答案:

答案 0 :(得分:2)

尝试使用SP_MSForEachDB过程..

exec sp_msforeachdb  'Your Query here'
相关问题