加入2个加入的表

时间:2017-07-30 21:17:16

标签: mysql join

我想加入以前加入的以下2个表,以便我可以看到结果,它在同一个窗口中并排显示Active和Inactive Subscription。怎么样?

表1(订阅表)

CUSTOMER ID | NAME | StartDate |结束日期

表2(客户表)

CUSTID | ......(不自由)

  

这将为我提供活动嫌疑人数

Select      T1.CustomerID, T1.Name, COUNT(CustomerID) [# Active Subscription]
FROM        #Customer T1
INNER JOIN  #Subscription AS T2
ON          T1.CustomerID = T2.CustID
WHERE       (T2.EndDate >= CURRENT_TIMESTAMP)
GROUP BY    T1.CustomerID, T1.Name
  

这会给我一些非必要的嫌疑人

Select      T1.CustomerID, T1.Name, COUNT(CustomerID) [# Inactive Subscription]
FROM        #Customer T1
INNER JOIN  #Subscription AS T2
ON          T1.CustomerID = T2.CustID
WHERE       (T2.EndDate < CURRENT_TIMESTAMP)
GROUP BY    T1.CustomerID, T1.Name

〜&gt;&gt;希望查看CustomerID,名称,#Active订户,#Inactive Subscriber

〜&gt;&gt;既然他们在两个表中都有相同的CustomerID,那么我认为我们可以做另一个加入......但是不知道怎么写它。

1 个答案:

答案 0 :(得分:0)

您需要首先对派生表执行GROUP和JOIN,然后对输出执行CASE聚合

尝试这样的事情;

SELECT

CASE WHEN (T2.EndDate >= CURRENT_TIMESTAMP) THEN
T1.CustomerID END AS customer_id_active,
CASE WHEN (T2.EndDate >= CURRENT_TIMESTAMP) THEN
T1.Name END AS name_active,
CASE WHEN (T2.EndDate >= CURRENT_TIMESTAMP) THEN
COUNT(CustomerID) END AS count_customerID_active,

CASE WHEN (T2.EndDate < CURRENT_TIMESTAMP) THEN
T1.CustomerID END AS customer_id_inactive,
CASE WHEN (T2.EndDate < CURRENT_TIMESTAMP) THEN
T1.Name END AS name_inactive,
CASE WHEN (T2.EndDate < CURRENT_TIMESTAMP) THEN
COUNT(CustomerID) END AS count_customerID_inactive,

FROM
(SELECT * FROM #Customer AS T1 INNER JOIN #Subscription AS T2 GROUP BY T1.CustomerID, T1.Name) AS derived_table