0

我目前正在运行以下查询(见下文。)但是,当我执行相同的值时,会为 totalusers、activeusers 和suspendedusers 中的多行返回相同的值。但是,当涉及到总登录时,这些值是唯一的。这是他们可能发生这种情况的一个原因,并且是他们解决问题的一种方法。如果它有助于我使用带有 postgre sql 驱动程序的工具 sql workben。

干杯

SELECT
    company.companyStatus,
    company.CompanyId,
    company.companyName,
    select 
        count(distinct UserID) 
        From Users 
            inner join company 
                on Users.CompanyID = Company.CompanyId
        where Users.Companyid = company.Companyid
        as TotalUsers,
    select sum(case when userstatusid =2 then 1 else 0 end)
        from users 
            inner join company 
                on users.companyid = company.companyid
        where users.companyid = company.companyid) 
        as ActiveUsers,
    select sum(case when userstatusid = 3 then 1 else 0 end)
        from users 
            inner join company 
                on users.companyid = company.companyid
        where users.companyid = company.companyid) 
        as SuspendedUsers,
    (Select COUNT (distinct usersessionid)
    From UserSession 
        inner join users  
                on usersession.UserID=users.UserID
    where usersession.UserID=users.UserID  
        and users.companyid= company.CompanyID) 
        as TotalLogin,
from  Company 
4

2 回答 2

0

这是因为您的 TotalUsers、ActiveUsers 和 SuspendedUsers 查询都在使用他们自己的(不受限制的)Company 表副本,而您的 TotalLogin 正在使用您从中选择的主实例。这意味着您看到的 TotalLogin 数字是针对该特定公司的,但其他字段是针对所有公司的。

大概你想要的东西更像:

   SELECT 
   company.companyStatus,
   company.CompanyId,
   company.companyName,
   count(distinct u.UserID) TotalUsers,
   sum(case when u.userstatusid =2 then 1 else 0 end) ActiveUsers,
   sum(case when u.userstatusid = 3 then 1 else 0 end) SuspendedUsers,
   count(distinct u.usersessionid) TotalLogin
   from  Company 
   inner join Users on Users.CompanyID = Company.CompanyId
于 2013-07-08T14:31:06.407 回答
0

原因是您company在这些计算的子查询中。

我更喜欢from尽可能在子句中包含表引用,您可以编写此查询将所有内容移至from子句:

   SELECT c.companyStatus, c.CompanyId, c.companyName,
          uc.Totalusers, uc.Activeusers, uc.Suspendedusers, ucs.TotalLogin
   from  Company c left outer join
         (select u.companyid,
                 COUNT(distinct userid) as Totalusers,
                 SUM(case when userstatusid = 2 then 1 else 0 end) as ActiveUsers,
                 sum(case when userstatusid = 3 then 1 else 0 end) as Suspendedusers
          from users u
          group by u.companyid
         ) uc
         uc.companyid = c.companyId left outer join
         (select u.companyid, COUNT(distinct usersessionid) as TotalLogin
          from UserSession us inner join
               users u
               on us.UserID = u.UserID
         ) ucs
         on ucs.companyid = c.companyid;

这也应该加快查询速度,因为它不必多次执行相同的工作。

于 2013-07-08T14:31:10.907 回答