2017-08-07 80 views
0

我擔心我已經離開了mysql太久,並且我要掉下一個兔子洞。根據條件從另一個表中減去從原始表列中刪除的數據的總計結果

client_sessions

id  cid  sessions  date 
------------------------------------------ 
1  102   5  01/07/2017 
2  102   3  01/08/2017 
3  141   5  29/07/2017 

用戶102有可從2017年1月7日ID 5個會話 - 1個 用戶102有可從2017年1月8日ID 3個會話 - 2

client_sessions_history

id  sid  date 
---------------------------- 
1  1  03/07/2017 
2  1  07/07/2017 
3  1  14/07/2017 
4  1  21/07/2017 
5  1  27/07/2017 
6  2  01/08/2017 

sid是來自client_sessions的id,這裏有5個用於1個 和1個來自2.

結果我想要的是:

date   remaining 
----------------------------- 
01/07/2017   0 
01/08/2017   2 

這將是從獨特的client_sessions按日期減去client_sessions_history唯一的會話總數會議由SID

我試過以下,但我一直在進行圍繞着圈子。

select a.sessions, a.id, (select count(distinct sid) from client_sessions_history where b.sid = a.id) as remaining from client_sessions as a, client_sessions_history as b where a.cid = 102 

基本上我想獲得剩餘總量爲CID 102

+1

我不明白你怎麼在你的預期輸出到達。你能解釋那裏的邏輯嗎? –

+0

對不起,今天有點累我編輯了這個問題,可能會更有意義謝謝:) – jbyrne2007

回答

1

計數明顯和組創建表/插入數據

CREATE TABLE client_sessions 
    (`id` INT, `cid` INT, `sessions` INT, `date` VARCHAR(10)) 
; 

INSERT INTO client_sessions 
    (`id`, `cid`, `sessions`, `date`) 
VALUES 
    (1, 102, 5, '01/07/2017'), 
    (2, 102, 3, '01/08/2017'), 
    (3, 141, 5, '29/07/2017') 
; 


CREATE TABLE client_sessions_history 
    (`id` INT, `sid` INT, `date` VARCHAR(10)) 
; 

INSERT INTO client_sessions_history 
    (`id`, `sid`, `date`) 
VALUES 
    (1, 1, '03/07/2017'), 
    (2, 1, '07/07/2017'), 
    (3, 1, '14/07/2017'), 
    (4, 1, '21/07/2017'), 
    (5, 1, '27/07/2017'), 
    (6, 2, '01/08/2017') 
; 

您需要創建一個交付表whe您是否計算了客戶歷史記錄會話。

查詢

SELECT 
    client_sessions.date 
, (client_sessions.sessions - client_sessions_grouped.client_sessions_history_sid_count) AS remaining 
FROM ( 

    SELECT 
     client_sessions.id 
    , COUNT(client_sessions_history.sid) AS client_sessions_history_sid_count 
    FROM 
    client_sessions 
    INNER JOIN 
    client_sessions_history 
    ON 
    client_sessions.id = client_sessions_history.sid 
    GROUP BY 
    client_sessions.id 
) 
AS 
    client_sessions_grouped 
INNER JOIN 
    client_sessions 
ON 
    client_sessions.id = client_sessions_grouped.id 

WHERE 
    client_sessions.cid = 102 

結果

date  remaining 
---------- ----------- 
01/07/2017   0 
01/08/2017   2 
+0

現貨謝謝。 – jbyrne2007

0

可能是你需要

select month(date), count(a.distinct sid) 
    from client_sessions_history a 
    inner join client_sessions b on a.sid = b.id 
    where b.cid= 102 
    group by month(date) 
+0

函數mount是什麼? –

+0

... @RaymondNijland非常感謝...月...不裝... – scaisEdge

0

嘗試此查詢:

SELECT 
    date , 
    (sessions - (SELECT COUNT(*) FROM client_sessions_history WHERE sid = client_sessions.id)) AS remaining 

FROM client_sessions 
WHERE cid = 102 
相關問題