下面是項目中按照男女年齡段統計的核心sql代碼:
COUNT(tr.id)AS '體檢總人數', SUM(CASE WHEN s.sex=1 THEN 1 ELSE 0 END) AS '男體檢總數', SUM(CASE WHEN s.sex=0 THEN 1 ELSE 0 END) AS '女體檢總數', SUM(CASE WHEN s.sex=1 AND tr.age >=18 AND tr.age <=29 THEN 1 ELSE 0 END) AS '男18--29歲', SUM(CASE WHEN s.sex=0 AND tr.age >=18 AND tr.age<=29 THEN 1 ELSE 0 END) AS '女18--29歲', SUM(CASE WHEN s.sex=1 AND tr.age <=45 AND tr.age>=30 THEN 1 ELSE 0 END) AS '男30--39歲', SUM(CASE WHEN s.sex=0 AND tr.age<=45 AND tr.age>=30 THEN 1 ELSE 0 END) AS '女30--39歲', SUM(CASE WHEN s.sex=1 AND tr.age <=50 AND tr.age>=46 THEN 1 ELSE 0 END) AS '男40--49歲', SUM(CASE WHEN s.sex=0 AND tr.age<=50 AND tr.age>=46 THEN 1 ELSE 0 END) AS '女40--49歲', SUM(CASE WHEN s.sex=1 AND tr.age <=60 AND tr.age>50 THEN 1 ELSE 0 END) AS '男50--59歲', SUM(CASE WHEN s.sex=0 AND tr.age<=60 AND tr.age>50 THEN 1 ELSE 0 END) AS '女50--59歲', SUM(CASE WHEN s.sex=1 AND tr.age <=70 AND tr.age>60 THEN 1 ELSE 0 END) AS '男60--69歲', SUM(CASE WHEN s.sex=0 AND tr.age<=70 AND tr.age>60 THEN 1 ELSE 0 END) AS '女60--69歲', SUM(CASE WHEN s.sex=1 AND tr.age <=80 AND tr.age>70 THEN 1 ELSE 0 END) AS '男70--79歲', SUM(CASE WHEN s.sex=0 AND tr.age<=80 AND tr.age>70 THEN 1 ELSE 0 END) AS '女70--79歲', SUM(CASE WHEN s.sex=1 AND tr.age >80 THEN 1 ELSE 0 END) AS '男80歲以上', SUM(CASE WHEN s.sex=0 AND tr.age>80 THEN 1 ELSE 0 END) AS '女80歲以上'
我拿其中一句解釋一下
SUM(CASE WHEN s.sex=1 AND tr.age >=18 AND tr.age <=29 THEN 1 ELSE 0 END) AS '男18--29歲',
先看sum的括號裡面的部分
case when sex = 1 and age>=18 and age <=29 then 1 else 0 end
它表示的含義是:如果性別為1(也就是男),並且年齡在18-29歲之間成立為1,不成立為0.
case和end 是一個關鍵字你可以理解為語句的開始和結束。
when相當於if做判斷,then就是判斷之後顯示的結果。如果成立顯示為1,不成立顯示為0
sum就是將各個值相加。形如:1+1+0+1+0+1+1+0+1+1
項目最後統計的結果截圖形如: