gpt4 book ai didi

mysql - 限制计数,其余为 "Others"

转载 作者:行者123 更新时间:2023-11-29 12:41:06 25 4
gpt4 key购买 nike

我正在计算要在饼图中显示的内容。我想仅显示实际投资类型的最高 6 个计数,其余的作为投资类型显示为“其他”。

SELECT i.investment_type AS investmentType,
COUNT(*) AS investmentCount
FROM investment i,
vertical v
WHERE v.vertical_name = i.investment_type
AND v.type = 'STR'
AND i.status_funding = 'o'
GROUP
BY i.investment_type
ORDER
BY investmentCount desc

上面的查询给了我一个结果

enter image description here

通过将 limit 6 添加到我得到的查询中

enter image description here

我需要的是另一行投资类型“其他”和投资计数“7”。

最佳答案

您可能想尝试以下操作:

    SELECT i.investment_type as investmentType,COUNT(*) as investmentCount FROM investment i,vertical v 
WHERE v.vertical_name =i.investment_type AND v.type='STR' AND i.status_funding ='o'
group by i.investment_type order by investmentCount desc
limit 6
UNION
SELECT "others" as investmentType, SUM(othersInvestmentCount) as investmentCount FROM (
SELECT COUNT(*) as othersInvestmentCount FROM investment i,vertical v
WHERE v.vertical_name =i.investment_type AND v.type='STR' AND i.status_funding ='o'
group by i.investment_type order by investmentCount desc
limit 6, 4294967296
)

我没有测试这个查询,如果您发现语法问题,可以编辑它。涉及三个实际查询,但它不应该太慢(如果不需要更快,则无需尝试更快)。

我假设您的数据库中的记录少于 2^32 条,这对于 MySQL 数据库来说似乎是一个非常合理的假设(但如果您觉得不安全,只需将其替换为 2^64)。

关于mysql - 限制计数,其余为 "Others",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26114510/

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