按“其他”分组,其中贡献较小的组包含在“其他”中 字段-MySQL

发布于 2024-07-18 11:32:41 字数 149 浏览 2 评论 0原文

我想按表中的一个项目进行分组,该项目具有相关的货币价值。 我可以将其计算为百分比,但是列表中通常有太多项目(太多而无用,例如在图表中)。 因此,我想将那些占总数少于 5% 的项目放入“其他”组。 有什么想法吗?

谢谢(使用 MySQL > v5)

I would like to GROUP BY an item in my table, which has an associated monetary value. This I can work out as a percentage, however there are often too many items in the list (too many to be useful, for example in a graph). Consequently, I would like to put those items that have a contribution to the total of less than say 5% into an 'Other' group. Any thoughts?

thanks (using MySQL > v5)

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

旧城空念 2024-07-25 11:32:41

看起来 UNION 可以提供帮助,例如(当然,取决于表的组织方式):

SELECT itemname, SUM(percent) AS pc FROM items
GROUP BY itemtype
HAVING SUM(percent) >= 0.05
UNION
SELECT 'Other', SUM(*) FROM
  (SELECT SUM(percent) FROM items
   GROUP BY itemtype
   HAVING SUM(percent) < 0.05)

如果您没有百分比字段,而只有(比如说)一个值字段(因此 % 需要动态计算为分数的 100 倍)项目的价值与总计)您可以从另一个嵌套的 SELECT 中获取总计,但在某些时候,正如其他受访者暗示的那样,可能值得切换到过程方法。

Looks like a UNION could help, e.g. (depending how your table's organized, of course):

SELECT itemname, SUM(percent) AS pc FROM items
GROUP BY itemtype
HAVING SUM(percent) >= 0.05
UNION
SELECT 'Other', SUM(*) FROM
  (SELECT SUM(percent) FROM items
   GROUP BY itemtype
   HAVING SUM(percent) < 0.05)

If you don't have a percent field but only (say) a value field (so the % needs to be dynamically computed as 100 times the fraction of an item's value to the grand total) you can get the grand total from yet another nested SELECT, but at some point it may be worth switching to procedural approaches as other respondents hint.

感悟人生的甜 2024-07-25 11:32:41

你询问了想法。 我可以为你编写 SQL,但我想知道(基于你的整体设计)你可能不会发现在 BL 或 UI 中做更多的工作(例如使用数组)来完成同样的事情会更容易。 一方面,SQL 必然比您希望的更复杂且效率更低。

You asked for thoughts. I could write the SQL for you, but I wonder (based on your overall design) you might not find it easier to do a little more work in the BL or UI, with an array for instance, to accomplish the same thing. For one thing, the SQL will necessarily be more complicated and less efficient than you might like.

残疾 2024-07-25 11:32:41

创建一个临时表并有两个插入语句,一个是您的主要内容,另一个是另一组,然后从临时表中选择所有内容。

create a temp table and have two insert statements, one of your primary stuff and one of the other group, then just select all from the temp table.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文