MYSQL 将结果从具有多行的多个子查询中分割出来

MYSQL divide results from multiple subqueries with multiple rows(MYSQL 将结果从具有多行的多个子查询中分割出来)
本文介绍了MYSQL 将结果从具有多行的多个子查询中分割出来的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个查询,第一个生成一个类似的表

I have two queries, the first one generating a table like

SELECT COUNT(channel) AS messages FROM Chats WHERE message LIKE '%word%' GROUP BY UNIX_TIMESTAMP(time) DIV 3600
+-----+
| 123 |
| 127 |
| 332 |
| 219 |
+-----+

第二个

SELECT COUNT(channel) AS messages FROM Chats GROUP BY UNIX_TIMESTAMP(time) DIV 3600
+-----+
| 222 |
| 579 |
| 590 |
| 377 |
+-----+

现在我想将第一个表中的所有结果除以第二个表中的相应值(结果四舍五入,必须手动计算):

Now I would like to divide all results from the first table by the corresponding value in the second one (results rounded, had to calculate it manually):

+------+
| 0.55 | #123/222
| 0.46 | #127/279
| 0.56 | #332/590
| 0.58 | #219/377
+------+

推荐答案

您可以通过以下查询来完成整个事情:

Here's one way you can accomplish the whole thing by the following query:

SELECT 
(dividendTable.messages / divisorTable.messages) AS result
FROM
(
    SELECT 
    firstTable.messages,
    @rn1 := @rn1 + 1 AS row_number
    FROM 
    (
        SELECT
            COUNT(channel) AS messages
        FROM Chats
        WHERE   message LIKE '%word%'
        GROUP BY    UNIX_TIMESTAMP(time) DIV 3600
    ) FirstTable, (SELECT @rn1 := 0) var1
) AS dividendTable
INNER JOIN
(   
    SELECT 
    secondTable.messages,
    @rn2 := @rn2 + 1 AS row_number
    FROM
    (
        SELECT 
            COUNT(channel) AS messages 
        FROM Chats 
        GROUP BY UNIX_TIMESTAMP(time) DIV 3600
    ) secondTable, (SELECT @rn2 := 0) var2
) AS divisorTable
ON dividendTable.row_number = divisorTable.row_number;

注意:

如果要将结果四舍五入到小数点后 2 位,则使用以下内容作为查询的第一行:

If you want the result rounded up to 2 digits after the decimal point then use the following as the first line of the query:

SELECT
ROUND((dividendTable.messages / divisorTable.messages),2) AS result

在这里演示

警告:您没有在查询中使用任何 ORDER BY.您可能会遇到随机行为.

Caution: You haven't used any ORDER BY in your query. You might get random behavior.

这篇关于MYSQL 将结果从具有多行的多个子查询中分割出来的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

Hibernate reactive No Vert.x context active in aws rds(AWS RDS中的休眠反应性非Vert.x上下文处于活动状态)
Bulk insert with mysql2 and NodeJs throws 500(使用mysql2和NodeJS的大容量插入抛出500)
Flask + PyMySQL giving error no attribute #39;settimeout#39;(FlASK+PyMySQL给出错误,没有属性#39;setTimeout#39;)
auto_increment column for a group of rows?(一组行的AUTO_INCREMENT列?)
Sort by ID DESC(按ID代码排序)
SQL/MySQL: split a quantity value into multiple rows by date(SQL/MySQL:按日期将数量值拆分为多行)