1、按substr(Startdate,1,4),plan,memberID分组
2、计算points的平均分
3、计算subste(Plan,1,3)=="Med"或medicinePaid>0的次数
- SELECT (SUBSTR(t1.Startdate,1,4)) AS Year
- ,t1.Plan
- ,t1.MemberID
- ,(AVG(COALESCE(t1.Points,0))) AS Points_AVG
- ,(SUM(CASE WHEN SUBSTR(t1.Plan,1,3) = "Med" or COALESCE(t1.MedicinePaid,0)> 0
- THEN 1
- ELSE 0
- END)
- ) AS MED_TIMES
-
- FROM TMP_TABLE t1
- GROUP BY SUBSTR(t1.Startdate,1,4),
- t1.Plan,
- t1.MemberID;
复制代码
结果集
Year Plan MemberID Points_AVG MED_TIMES
2014 COM A 114257 0.6 4
2014 Com A 675732 0 0
2014 Com B 234234 0 0
2014 Med A 114257 1 6
2014 Med A 118521 0.575 12
2014 Med A 155191 0 12
2014 Med A 342357 0 12
2014 Med A 675732 0 6
2014 Med A 753452 0 12
2014 Med A 883234 0 12
2014 Med B 185212 0.5 12
2015 COM B 114821 0.416666667 3
2015 Com A 155191 0 0
2015 Com A 234234 0 0
2015 Com A 456134 0 0
2015 Com B 183522 0 0
2015 Com B 253351 0 0
2015 Med A 155191 0 6
2015 Med A 183522 0 6
2015 Med A 456134 0 12
2015 Med A 523411 0 12
2015 Med B 114821 0.45 6
2015 Med B 155191 0 6
2015 Med B 253351 0 6
2015 Med B 342357 0 12
2015 Med B 456134 0 6