使用Group By子句连接2计数查询

时间:2016-02-05 06:38:52

标签: sql sql-server-2008 join count

我有2个查询
第一个是:

SELECT UserId, COUNT(CustomerId) AS Total
  FROM (SELECT *
          FROM Customer
         WHERE JoinYear = 2016 
           AND JoinMonth = 1
           AND JoinWeek = 2 
           AND JoinDay = 1) x
GROUP BY UserId

第二个是:

SELECT UserId, COUNT(CustomerId) AS Joined
  FROM (SELECT *
          FROM Customer
         WHERE JoinYear = 2016 
           AND JoinMonth = 1
           AND JoinWeek = 2 
           AND JoinDay = 1
           AND JoinStatus = 2) x
GROUP BY UserId

他们每个人都会产生

(first query)                (second query)

UserId | Total              UserId | Total
--------------              --------------  
   1   |  10                   1   |   2
   2   |  15                   2   |   5

我的问题是如何将它们加入到这样的表中?

Userid | Total | Joined
-----------------------
   1   |  10   |   2
   2   |  15   |   5

2 个答案:

答案 0 :(得分:1)

你的查询非常复杂,没有理由。

试试这个:

SELECT UserID, COUNT(*) Total, SUM(CASE WHEN JoinStatus = 2 THEN 1 END) Joined
FROM Customer
WHERE JoinYear = 2016 AND JoinMonth = 1 AND JoinWeek = 2 AND JoinDay = 1
GROUP BY UserID

这是展示此技术的SQLFiddle

每当您发现自己使用嵌套子查询时,请问自己这是否真的是强制性的。

答案 1 :(得分:-1)

其他oprion:

select  UserID, count(Total) as Total, count(Joind) as Joined
from    (
            select  UserId,COUNT(CustomerId) as Total, cast(0 as int) as Joined
            from    Customer
            where   JoinYear = 2016 and JoinMonth = 1 and JoinWeek = 2 and JoinDay = 1
            group by    UserID
            union all
            select  UserId,
                    cast(0 as int) as Total, count(CustomerId) as Joined Customer
            where   JoinYear = 2016 and JoinMonth = 1 and JoinWeek = 2 and JoinDay = 1  and JoinStatus = 2
            group by    UserId
        ) x
group by    x.UserID