2016-07-06 56 views
0

我將按照性別每年創建一個人口圖,並且該圖看起來像下面的圖像。 enter image description here獲取上一行中列的值並將其添加到下一行的下一列

但是我很難與查詢。

查詢

SELECT 
     year_added, 
     COUNT(case when gender='Male' then 1 end) as malecount, 
     COUNT(case when gender='Female' then 1 end) as femalecount, 
     COUNT(*) as totalcount 
    FROM tbl 
    WHERE status = 1 
    GROUP BY year_added 

結果

enter image description here

在結果中,2016男性計數爲4和陰計數是8。在2017年,我想的陽計數2016年的男性人數將增加到2017年,這意味着2017年男性人數將爲5,與女性人數和總人數相同。我在下面提供了一個結果應該是什麼樣子的圖片。你能幫我做些什麼,讓我繼續做圖表嗎?或者還有其他方法可以實現嗎?

enter image description here

+0

這些人大概是不朽的? – Strawberry

回答

2

試試這個:

SELECT 
    year_added, 
    @malecount_v := @malecount_v + malecount as malecount, 
    @femalecount_v := @femalecount_v + femalecount as femalecount, 
    @totalcount_v := @totalcount_v + totalcount as totalcount 
FROM (
    SELECT 
     year_added, 
     COUNT(case when gender='Male' then 1 end) as malecount, 
     COUNT(case when gender='Female' then 1 end) as femalecount, 
     COUNT(*) as totalcount 
    FROM tbl 
    WHERE status = 1 
    GROUP BY year_added 
    ORDER BY year_added 
) t1 
CROSS JOIN (SELECT @malecount_v := 0, @femalecount_v := 0, @totalcount_v := 0) t2 
+0

非常感謝! – dontknow

+1

這看起來不太合適 – Strawberry

+0

@Strawberry那麼你的建議是什麼? – Blank

-1

,你可以簡單地使用

WITH TableCount AS 
(
    SELECT 
     year_added, 
     COUNT(case when gender='Male' then 1 end) as malecount, 
     COUNT(case when gender='Female' then 1 end) as femalecount, 
     COUNT(*) as totalcount 
    FROM tbl 
    WHERE status = 1 
    GROUP BY year_added 
) 

和使用後下面的查詢

SELECT 
     SUM(malecount) as 'malecount', 
     SUM(femalecount) as 'femalecount', 
     SUM(totalcount) as 'totalcount' 
    FROM TableCount 

如果您正在使用MySql您可以使用臨時表來執行類似的CTE

CREATE TEMPORARY TABLE IF NOT EXISTS TableCount AS (
SELECT 
      year_added, 
      COUNT(case when gender='Male' then 1 end) as malecount, 
      COUNT(case when gender='Female' then 1 end) as femalecount, 
      COUNT(*) as totalcount 
     FROM tbl 
     WHERE status = 1 
     GROUP BY year_added 
) 

然後你就可以使用上面的查詢

SELECT 
     SUM(malecount) as 'malecount', 
     SUM(femalecount) as 'femalecount', 
     SUM(totalcount) as 'totalcount' 
    FROM TableCount 

創建表時,您可以使用TEMPORARY關鍵詞。 TEMPORARY 表僅對當前會話可見,並在會話關閉時自動丟棄 。這意味着兩個不同的會話可以使用相同的臨時表名稱,而不會與 相互衝突,或者與同名的現有非臨時表 衝突。 (現有表將隱藏,直到刪除臨時表 。)要創建臨時表,您必須具有CREATE TEMPORARY TABLES特權。

通過使用臨時表的概念就可以實現公用表表達式類型的功能在MySQL

+0

我想他想要一個總跑步數。 –

+1

目前尚不清楚。 –

+0

我不認爲MySQL支持公用表表達式。 –

0

在MySQL中,你可以用variables做到這一點,如:

SELECT 
    year_added, 
    (@iMalecount := (COUNT(CASE WHEN gender = 'Male' THEN 1 END) + @iMalecount)) AS malecount, 
    (@iFemalecount := (COUNT(CASE WHEN gender = 'Female' THEN 1 END) + @iFemalecount)) AS femalecount, 
    (@iTotalcount := (COUNT(gender) + @iTotalcount)) AS totalcount 
FROM tbl 
WHERE status = 1 
GROUP BY year_added 

但不是100%可以喲你可以閱讀文檔。

在其他SQL風格可能你需要一個存儲過程。

相關問題