3 回答
TA贡献1784条经验 获得超9个赞
如果您使用的是MYSQL 8.0及更高版本,则可以WITH用来创建两个表,即已创建的表和仅具有最大值的表。然后交叉连接两个表以将最大值添加到每一行。
您也可以选择Total / max_total以获得介于0和1之间的百分比。
WITH query_data AS (
SELECT
MONTHNAME(birthdatetr) AS Month_of_Birth,
MONTH(birthdatetr) AS number_of_month_of_birth,
COUNT(*) AS Total
FROM
tng_people
WHERE
MONTH(birthdatetr) > 0
GROUP BY
number_of_month_of_birth
),
max_count AS (
SELECT MAX(Total) AS max_total FROM query_data
)
SELECT query_data.*, max_count.max_total
FROM query_data CROSS JOIN max_count
ORDER BY
query_data.number_of_month_of_birth
对于mysql <8.0,您可以像这样连接两个表:
SELECT query_data.*, max_count.max_total
FROM (
SELECT
MONTHNAME(birthdatetr) AS Month_of_Birth,
MONTH(birthdatetr) AS number_of_month_of_birth,
COUNT(*) AS Total
FROM
tng_people
WHERE
MONTH(birthdatetr) > 0
GROUP BY
number_of_month_of_birth
) query_data
CROSS JOIN (
SELECT MAX(tmp_max.Total) AS max_total FROM
(
SELECT
MONTHNAME(birthdatetr) AS Month_of_Birth,
MONTH(birthdatetr) AS number_of_month_of_birth,
COUNT(*) AS Total
FROM
tng_people
WHERE
MONTH(birthdatetr) > 0
GROUP BY
number_of_month_of_birth
) tmp_max
) max_count
ORDER BY
query_data.number_of_month_of_birth
TA贡献1871条经验 获得超8个赞
我不知道我的想法是否正确,但我相信您可以使用子查询
SELECT
MONTHNAME(birthdatetr) AS Month_of_Birth,
MONTH(birthdatetr) AS number_of_month_of_birth,
COUNT(*) AS Total,
(select count(*) FROM tng_people
WHERE month(birthdatetr) > 0
GROUP BY month(birthdatetr)
ORDER BY count(*) DESC
limit 1) as birthmax
FROM
tng_people
WHERE
MONTH(birthdatetr) > 0
GROUP BY
number_of_month_of_birth
ORDER BY
number_of_month_of_birth
TA贡献1852条经验 获得超7个赞
一种解决方案是子查询,该查询的计数最高。
SELECT monthname(birthdatetr) month_of_birth,
month(birthdatetr) number_of_month_of_birth,
count(*) total,
(SELECT count(*)
FROM tng_people
WHERE month(birthdatetr) > 0
GROUP BY month(birthdatetr)
ORDER BY count(*) DESC
LIMIT 1) overall_total
FROM tng_people
WHERE month(birthdatetr) > 0
GROUP BY month(birthdatetr)
ORDER BY month(birthdatetr);
- 3 回答
- 0 关注
- 179 浏览
添加回答
举报