2015-10-08 63 views
3

我有一個問題,我需要多次加入同一個表並計算JOINS。SQL count加入不同的多列

這裏的數據庫設置(SQL Fiddle ):

CREATE TABLE state 
(
    [t_id] int, 
    [true_id] int, 
    [false_id] int, 
    [msg] varchar(32) 
); 

INSERT INTO state 
    (t_id, true_id, false_id, msg) 
VALUES 
    (5, 6, 7, 'CASE_1'), 
    (10, 11, 12, 'CASE_2'), 
    (20, 21, 22, 'CASE_N'), 
    (30, 31, 32, 'FOOOO'); 

CREATE TABLE step 
(
     [id] int, 
     [f_id] int, 
     [state_type] int, 
     [state_value] int 
); 

INSERT INTO step 
    (id,f_id,state_type, state_value) 
VALUES 
    (1, 5, 5, 7), 
    (2, 5, 5, 7), 
    (3, 5, 5, 6), 

    (4, 5, 10, 12), 
    (5, 5, 10, 12), 
    (6, 5, 10, 11), 

    (7, 6, 10, 12), 
    (8, 6, 10, 12), 

    (9, 7, 20, 21), 
    (10, 7, 20, 21), 

    (11, 7, 30, 32), 
    (12,7, 30, 31); 

這裏是我當前的查詢:

SELECT state.msg, 
    COUNT(state_true.true_id) AS Trues, 
    COUNT(state_false.false_id) AS Falses 
FROM state 
    INNER JOIN step ON state.t_id = step.state_type 
    LEFT OUTER JOIN state AS state_true ON step.state_value = state_true.true_id 
    LEFT OUTER JOIN state AS state_false ON step.state_value = state_false.false_id 
GROUP BY state.msg, step.f_id 

在這裏,我得到什麼:

msg  Trues Falses 
CASE_1 1  2 
CASE_2 1  2 
CASE_2 0  2 
CASE_N 2  0 
FOOOO 1  1 

在這裏,我需要:

msg  Trues Falses 
CASE_1 1  0 
CASE_2 1  1 
CASE_N 1  0 
FOOOO 1  0 

對於解釋:

我需要算多少trues和失敗是每爲state_type和F_ID組合。

有6個條目f_id = 5 - >(1,2,3,4,5,6)。如果有一個條目與(f_id,state_type)組合相同,則只應計入最後一個條目。因此,對於f_id 5,不應將條目1,2,4,5納入計數中,因爲它們是將由36覆蓋

所以處理第6項之後應該有CASE_1true => 1false => 0CASE_2true => 1false => 0

__ __編輯

TABLE step: 

(1, 5, 5, 7), -- do not count 
(2, 5, 5, 7), -- do not count 
(3, 5, 5, 6), -- this is the last entry with 
       -- (f_id,state_type) => (5,5) combination. 
       -- it overwrites the 2 previous ones => count CASE_1 true 

(4, 5, 10, 12), -- do not count 
(5, 5, 10, 12), -- do not count 
(6, 5, 10, 11), -- count CASE_2 true 

(7, 6, 10, 12), -- do not count 
(8, 6, 10, 12), -- count CASE_2 false 

(9, 7, 20, 21), -- do not count 
(10, 7, 20, 21), -- count CASE_N false 

(11, 7, 30, 32), -- do not count 
(12,7, 30, 31); -- count FOOOO true 
+0

非常好的表達問題的方式(使用SQL小提琴和創建腳本)。但是,我很難理解解釋。 – DarkKnight

+0

很好,但我也有同感:( – mohan111

+0

你爲什麼加入true_id和false_id ..是否需要? – DarkKnight

回答

2

我不知道我完全理解你的意圖,但也許查詢下面可能是你想要的?鑑於您的示例數據,它似乎產生正確的輸出。

SELECT state.msg, 
    SUM(CASE WHEN true_id = state_value THEN 1 ELSE 0 END) AS Trues, 
    SUM(CASE WHEN false_id = state_value THEN 1 ELSE 0 END) AS Falses 
FROM state 
JOIN step ON state.t_id = step.state_type 
JOIN (SELECT MAX(id) mid FROM step GROUP BY f_id, state_type) a ON a.mid = step.id 
GROUP BY state.msg; 

請試試看。如果我誤解了我會刪除答案。

+1

這產生了OP請求的值:http://sqlfiddle.com/#!3/738b4/14。 –

+1

是的,這看起來不錯:) – eddy