2016-02-05 56 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