为sql中的多行返回相同的值,但不是所有列

时间:2013-07-08 14:21:57

标签: sql

我目前正在运行以下查询(见下文)。 但是,当我执行相同的值时,将返回totalusers,activeusers和suspendedusers中的多行。 但是,当涉及到完全登录时,值是唯一的。 他们之所以能够实现这一点,是他们解决问题的方法。如果它有助于我使用工具sql workben与postgre sql驱动程序。

干杯

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 

2 个答案:

答案 0 :(得分: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

答案 1 :(得分: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;

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