gpt4 book ai didi

mysql - 如何在mysql中进行序号排名

转载 作者:行者123 更新时间:2023-11-29 06:37:00 27 4
gpt4 key购买 nike

我有这样的数据:

id | md_name      | total_visit
===+==============+============
1 | Nunu Nugraha | 33
2 | Erwin | 32
3 | Tri Sulistyo | 35
4 | Risdianto | 24
5 | Erma | 22
6 | Dwi Sabana | 19
7 | Ernayanti | 26
8 | Ali | 10
9 | Partini | 13

我使用如下连接代码得到了上述结果:

SELECT datamd.id as id,
datamd.nama_md as md_name,
COUNT(R.id) as total_visit
FROM datamd
LEFT JOIN
(
SELECT id, idmd
FROM rincian_kunjungan WHERE status='1' AND MONTH(tanggal_kunjungan)='$bulan' AND YEAR(tanggal_kunjungan)='$tahun'
) AS R
ON datamd.id = R.idmd WHERE status=1 AND level=8 GROUP BY datamd.id ORDER BY datamd.id

我想成为这样的人:

rank | id | md_name      | total_visit
=====+====+==============+============
1 | 3 | Tri Sulistyo | 35
2 | 1 | Nunu Nurgaha | 33
3 | 2 | Erwin | 32
4 | 7 | Ernayanti | 26
5 | 4 | Risdianto | 24
6 | 5 | Erma | 22
7 | 6 | Dwi Sabana | 19
8 | 9 | Partini | 13
9 | 8 | Ali | 10

这里的 friend 可以帮助我吗,我尝试过使用下面的代码,但在排名栏中它不合适

SET @number = 0;
SELECT @number:=@number+1 as rank, datamd.id as id,
datamd.nama_md as md_name,
COUNT(R.id) as total_visit
FROM datamd
LEFT JOIN
(
SELECT id, idmd
FROM rincian_kunjungan WHERE status='1' AND MONTH(tanggal_kunjungan)='$bulan' AND YEAR(tanggal_kunjungan)='$tahun'
) AS R
ON datamd.id = R.idmd WHERE status=1 AND level=8 GROUP BY datamd.id ORDER BY rank ASC

最佳答案

您可以整天与用户变量战斗或在MySQL中模拟密集排名函数,如下所示:

SELECT main.id, main.md_name, main.total_visit, COUNT(DISTINCT prev.total_visit) + 1 AS rank
FROM datamd AS main
LEFT JOIN datamd AS prev ON prev.total_visit > main.total_visit
GROUP BY main.id, main.md_name, main.total_visit
ORDER BY rank

用原始查询中的子查询替换上述查询中的“表”:

SELECT datamd.id, datamd.nama_md, main.total_visit, COUNT(DISTINCT prev.total_visit) + 1 AS rank
FROM datamd
LEFT JOIN (
SELECT idmd, COUNT(*) AS total_visit
FROM rincian_kunjungan
WHERE status = '1' AND MONTH(tanggal_kunjungan) = $bulan AND YEAR(tanggal_kunjungan) = $tahun
GROUP BY idmd
) AS main ON datamd.id = main.idmd
LEFT JOIN (
SELECT COUNT(*) AS total_visit
FROM rincian_kunjungan
WHERE status = '1' AND MONTH(tanggal_kunjungan) = $bulan AND YEAR(tanggal_kunjungan) = $tahun
GROUP BY idmd
) AS prev ON prev.total_visit > main.total_visit
GROUP BY datamd.id, datamd.nama_md, main.total_visit
ORDER BY rank

关于mysql - 如何在mysql中进行序号排名,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53368432/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com