2016-02-05 39 views
0

我有2个查询
第一个是:
加入2计数查询与GROUP BY子句

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 
+0

你可以试试这个 '选择x1.UserId,COUNT(x1.CustomerId)为总,COUNT(x2.CustomerId)AS加入 FROM(SELECT * FROM客户WHERE JoinYear = 2016和JoinMonth = 1 AND JoinWeek = 2 AND AND JoinDay = 1)x1 LEFT JOIN(SELECT * FROM Customer WHERE JoinYear = 2016 AND JoinMonth = 1 AND JoinWeek = 2 AND JoinDay = 1 AND JoinStatus = 2)x2 ON x2.UserId = x1.UserId' –

回答

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这种技术。

每当你发现自己有嵌套的子查询时,问问自己是否真的是强制性的。

+0

不行,查询不是我搜索的 –

+0

@ JNTX1412怎么来的? – Amit

+0

嘿,我很抱歉,太集中在你的小提琴中,这也是我为 –

-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 
+0

don'不要急,你的代码有一些错误,如'JoinMonth = 1 ='等 –

+0

我相信你可以纠正语法错误,如果你有这个想法和位置 – JassyJov