简体   繁体   English

使用MySQL和PHP计算一定范围内数字的总结果

[英]Count total results of a number within a certain range using MySQL and PHP

The goal of the project is to check the total character count of a textarea field and compare the conversion rate against historical data. 该项目的目标是检查文本区域的总字符数,并将转换率与历史数据进行比较。 Simply: Person X enters 300 characters, and I want to see the conversion rate of previous people who entered between 260 and 340 characters. 简而言之:X人输入了300个字符,我想看看以前输入260至340个字符的人的转换率。

Here's a working MySQL query: 这是一个有效的MySQL查询:

SELECT 
  COUNT(*) AS total_count, 
  SUM(converted) AS total_converted, 
  (SUM(converted) / count(*)) * 100 AS conversion_rate, text_length
FROM my_table WHERE text_length IS NOT NULL
GROUP BY text_length div 40

This works fine for lower numbers, but at a certain point (like over 400 characters), I'd like to just lump them all together. 这对于较小的数字效果很好,但是在某个点(例如超过400个字符),我想将它们全部在一起。 Is there a way to check if the 'text_length' is over a certain value and then just COUNT everything above it? 有没有一种方法可以检查'text_length'是否超过某个值,然后仅检查上面的所有内容?

Also, if anyone has any suggestions for a better overall approach, I'd be happy to try that, too. 另外,如果有人对更好的整体方法有任何建议,我也很乐于尝试。 Thanks! 谢谢!

Using UNION, you could do this: 使用UNION,您可以执行以下操作:

(SELECT 
  COUNT(*) AS total_count, 
  SUM(converted) AS total_converted, 
  (SUM(converted) / count(*)) * 100 AS conversion_rate, text_length
FROM my_table
WHERE text_length <= 400
GROUP BY text_length div 40)
UNION
(SELECT 
  COUNT(*) AS total_count, 
  SUM(converted) AS total_converted, 
  (SUM(converted) / count(*)) * 100 AS conversion_rate, 401 AS text_length
FROM my_table
WHERE text_length > 400)

Notice that I've also removed the WHERE text_length IS NOT NULL which is no longer needed. 请注意,我还删除了不再需要的WHERE text_length IS NOT NULL Your text_lengths that are greater than 400 will be grouped as text_length 401. 您大于400的text_lengths将被分组为text_length 401。

How about 怎么样

GROUP BY (text_length > 400), CAST((text_length / 40) AS INTEGER)

That would make anything with 401+ characters group together into a single group, and then anything 400 or less get grouped by the 40 char divisions. 这将使具有401+个字符的所有内容组合成一个组,然后将400个或更少的内容按40 char分区分组。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM