将多个计数查询组合到单个查询中

时间:2017-08-22 09:28:03

标签: sql sql-server

在SQL中,我有一组查询,它们返回来自不同表的计数值,具有不同的条件,如下面的

SELECT COUNT(DISTINCT GroupUserID) AS KnownUsers 
FROM Table A 
WHERE ...

SELECT COUNT(DISTINCT GroupUserID) AS UnKnownUsers 
FROM TableB  
WHERE (a different condition)

SELECT 
    COUNT(DISTINCT ManagerID) AS Managers, 
    COUNT(DISTINCT LeadID) AS TeamLeads 
FROM
    TableX  
WHERE 
    (condition)

是否有任何方法或查询可用于将所有3个SQL查询合并为一个将返回4列的SQL查询?

  KnownUsers    UnKnownUsers   Managers    TeamLeads

4 个答案:

答案 0 :(得分:3)

试试这个

    SELECT  (select COUNT(distinct GroupUserID) as KnownUsers from Table A WHERE ...) as KnownUsers ,   

    (SELECT  COUNT(distinct GroupUserID) as UnKnownUsers from TableB  WHERE (a   different condition)) as UnKnownUsers,

    (SELECT  COUNT(distinct ManagerID) from TableX  WHERE (condition)) as Managers, 
 (SELECT  COUNT(distinct LeadID) as TeamLeads from TableX  WHERE (condition)) as TeamLeads 

答案 1 :(得分:2)

是。使用子查询选择它们:

SELECT
    KnownUsers=(SELECT  COUNT(distinct GroupUserID) from Table A WHERE ...),
    UnKnownUsers=(SELECT  COUNT(distinct GroupUserID) from TableB  WHERE (a   different condition)),
    Managers=(SELECT  COUNT(distinct ManagerID) from TableX  WHERE (condition)),
    TeamLeads=(SELECT  COUNT(distinct LeadID) from TableX  WHERE (condition));

答案 2 :(得分:1)

select *
from 
(
    select COUNT(1) TotalRecord,'KnownUsers' as Users from TableA 
    union all
    select COUNT(1) TotalRecord,'UnKnownUsers' as Users from TableB 
    union all
    select COUNT(1) TotalRecord,'TeamLeads' as Users from TableX
    union all
    select COUNT(1) TotalRecord,'Managers' as Users from TableX
)
 UserDetails
pivot
(
  sum(TotalRecord)
  for Users in ([KnownUsers], [UnKnownUsers], [TeamLeads], [Managers])
) piv;

答案 3 :(得分:0)

使用它会比使用子查询更快。

SELECT  COUNT(DISTINCT ManagerID) AS Managers ,
        COUNT(DISTINCT LeadID) AS TeamLeads ,
        Tmp.KnownUsers ,
        Tmp1.UnKnownUsers
FROM    TableX
        CROSS APPLY ( SELECT    COUNT(DISTINCT GroupUserID) AS KnownUsers
                      FROM      TableA
                      WHERE (Condition)
                    ) Tmp
        CROSS APPLY ( SELECT    COUNT(DISTINCT GroupUserID) AS UnKnownUsers
                      FROM      TableB
                      WHERE (a different condtion)
                    ) Tmp1
WHERE (TableXCondition)