今天写了一个超长的(MySql)SQL语句,为了统计医生的综合名次:
统计名次逻辑:使用到了@jznum声明一个变量
医生有三个名次指标:接诊人数、金额、复诊人数
首先:要得出这三个指标的名次(得出三个排名:接诊人数、金额、复诊人数)
然后:把每个医生的三个名次相加(接诊人数名次+金额名次+复诊人数名次),作为每个医生的“综合名次”。
最后:根据每个医生的“综合名次”,排序,得出前十名。
给出SQL:
select je.ysmc,jerank,fzrank,jzrank,@sum:=jerank+fzrank+jzrank as rank from
(select @jenum:=@jenum+1 as jerank, t.ysmc
from
(select ysmc,SUM(je) as sumje from TB_DPSTAT_YSJXJXZH
where datediff(curdate(),tjrq)<365 and datediff(curdate(),tjrq)>0 GROUP BY YSgh ORDER BY sumje Desc)
t,
(select @jenum:=0) B order by t.sumje desc) je,
(
SELECT
@fznum :=@fznum + 1 AS fzrank,
t.ysmc,
t.sumfzrs
FROM
(
SELECT
ysmc,
SUM(fzrs) AS sumfzrs
FROM
TB_DPSTAT_YSJXJXZH
WHERE
datediff(curdate(), tjrq) < 365
AND datediff(curdate(), tjrq) > 0
GROUP BY
YSgh
ORDER BY
sumfzrs DESC
) t,
(SELECT @fznum := 0) B
ORDER BY
t.sumfzrs DESC
) fz,
(
SELECT
@jznum :=@jznum + 1 AS jzrank,
t.ysmc,
t.sumrjjzrs
FROM
(
SELECT
ysmc,
SUM(RJJZRS) AS sumrjjzrs
FROM
TB_DPSTAT_YSJXJXZH
WHERE
datediff(curdate(), tjrq) < 365
AND datediff(curdate(), tjrq) > 0
GROUP BY
YSgh
ORDER BY
sumrjjzrs DESC
) t,
(SELECT @jznum := 0) B
ORDER BY
t.sumrjjzrs DESC
) jz
WHERE
je.ysmc = fz.ysmc
AND fz.ysmc = jz.ysmc
ORDER BY
rank
LIMIT 10
小结:
知识点 1 :
用@jznum声明一个变量,来根据已经排好序的数据,添加一列新的序号列。
select @jznum:=@jznum+1 as rank, st.xm from
( select * from StudentInfo order by fenshu desc) st, (select @jznum:=0) B order by rank
知识点 2:
在使用sql函数时,尽量不要把函数与表中的字段关联起来,这样的话,这个字段所带的索引就会失效。
例如:上面的SQL语句中所涉及的datediff函数,
用:
CURDATE()>tjrq and DATE_ADD(CURDATE(),INTERVAL -365 DAY)<tjrq
来代替。这样函数和字段脱离,就不会影响字段的索引功能。