2013-11-14 53 views
0

很難用單詞解釋的類型,但我試圖按照類型分組數據,並且通過另一個表來加入數據以獲得結果。我的SqlFiddle例子。在分組查詢中計算相同字段值的MySQL結果

下面是一個例子的數據:

(鏈接表)[ID,類型,創建]

(1, 1, '2013-01-01') 
(2, 1, '2013-01-02') 
(3, 2, '2013-01-03') 
(4, 4, '2013-01-04') 

(信息表)[ID,link_id,資訊類型,帳簿,蜱]

(1, 1,1,10,15) 
(1, 2,2,20,17) 
(1, 3,1,12,14) 
(1, 4,2,18,21) 

我希望的結果是:[TYPE_A,TYPE_B,帳簿,蜱]

(1, 1, 30, 32) 
(1, 0, 12, 14) 
(0, 1, 18, 21) 

我越來越

(2, 2, 30, 32) 
(1, 1, 12, 14) 
(1, 1, 18, 21) 

這裏的結果是我的查詢我使用

SELECT 
    COUNT(i.info_type) as type_a, 
    COUNT(i.info_type) as type_b, 
    SUM(i.tally) as tally, 
    SUM(i.tick) as tick 
FROM link l 
JOIN info i ON (l.id = i.link_id) 
WHERE l.created BETWEEN '2013-01-01' AND '2014-01-01' 
GROUP BY l.type 

總而言之我想在一個日期範圍內的所有鏈接,通過link.type 分組然後返回info_type的數量等於1作爲type_a,等於2作爲type_b ,以及Tally和tick的總和是正確的。這只是type_a和type_b結果 是錯誤的。

+0

「鏈接」表中的數據只有2列,而您的描述有3個。 –

+0

如果我看到這些更正,我可能犯了一個錯誤並錯過了幾個字段。謝謝你指出。 – John

+0

也修正了這個問題。謝謝。 – John

回答

1
SELECT 
    SUM(i.info_type = 1) AS type_a, 
    SUM(i.info_type = 2) AS type_b, 
    SUM(i.tally) AS tally, 
    SUM(i.tick) AS tick 
FROM link l 
JOIN info i ON l.id = i.link_id 
WHERE l.created BETWEEN '2013-01-01' AND '2014-01-01' 
GROUP BY l.type ; 

SUM(i.info_type = 1)是一個MySQL的成語。更可讀的SQL代碼如下:

SELECT 
    COUNT(CASE WHEN i.info_type = 1 THEN 1 ELSE NULL END) AS type_a, 
    COUNT(CASE WHEN i.info_type = 2 THEN 1 ELSE NULL END) AS type_b, 
    SUM(i.tally) AS tally, 
    SUM(i.tick) AS tick 
FROM link l 
JOIN info i ON l.id = i.link_id 
WHERE l.created BETWEEN '2013-01-01' AND '2014-01-01' 
GROUP BY l.type ; 

在另一方面,我不認爲你應該使用BETWEEN的日期。現在的情況將包括整整一年加上我懷疑可能有用的一天。您可以改用:

WHERE l.created >= '2013-01-01' 
    AND l.created < '2014-01-01' -- notice the missing equal sign here 

,這將導致在整整一年的時間間隔,不管是否createdDATE類型,DATETIMETIMESTAMP的。

0

我想這你需要什麼

SELECT 
    SUM(CASE WHEN MOD(I.INFO_TYPE,2) = 0 THEN 1 ELSE 0 END) as type_B, 
    SUM(CASE WHEN MOD(I.INFO_TYPE,2) <> 0 AND MOD(I.INFO_TYPE, 1) = 0 
    THEN 1 ELSE 0 END) as type_A, 
SUM(I.TALLY) AS TALLY, SUM(I.TICK) AS TICK 
FROM link l 
JOIN info i ON (l.id = i.link_id) 
WHERE l.created BETWEEN '2013-01-01' AND '2014-01-01' 
GROUP BY L.TYPE 
+0

否type_a和type_b可以是0,2,並根據返回的數量不計算靜態結果繼續計數。 – John

+0

隨着表格的增長,每行可以產生更大的結果。由於它按link.type分組。它只計算該組中有多少組爲info_type 1和2,因此組中可能有許多組,type_a和type_b可能爲0,如果該條目反映了這樣的結果,則可以是4。 – John

+0

您需要對查詢進行任何修改?如果是的話,你需要修改什麼/ – Santhosh