[英]MySQL Calculate percentage difference (not change) between 2 columns based on SUM column alias
I have 2 table t1 where price and item type is stored with an ENUM value and t2 where the sold quantity is stored.我有 2 个表 t1,其中价格和项目类型存储有 ENUM 值,t2 存储销售数量。 I have a query to calculate the total sale (price * qty) but I need to calculate the difference between the 2 resulted numbers.我有一个查询来计算总销售额(价格 * 数量),但我需要计算两个结果数字之间的差异。
The calculation formula for difference between 2 numbers should be: 2数差的计算公式应为:
((N1 - N2) / ((N1 + N2) / 2)) * 100 ((N1 - N2) / ((N1 + N2) / 2)) * 100
Using the above formula I need to calculate the difference in percentage between N1 and N2.使用上述公式,我需要计算 N1 和 N2 之间的百分比差异。 Both numbers are the result of 2 separate SUM cases based on 2 ENUM values in col_type (please see below)这两个数字都是基于 col_type 中的 2 个 ENUM 值的 2 个单独的 SUM 情况的结果(请参见下文)
SELECT
CONCAT('£ ',SUM(CASE WHEN t1.col_type = 'N1' THEN t2.qty * t1.price ELSE 0 END)) AS 'Total N1',
CONCAT('£ ',SUM(CASE WHEN t1.col_type = 'N2' THEN t2.qty * t1.price ELSE 0 END)) AS 'Total N2'
FROM t2
INNER JOIN t1
ON t2.col_id = t1.col_id
The resulted output should be like:结果输出应该是这样的:
+----------+----------+------------------------+
| Total N1 | Total N2 | Diff between N1 and N2 |
+----------+----------+------------------------+
| 3765.50 | 3246.15 | 14.81% |
+----------+----------+-----------------------
My question is how do I pass the values of N1 and N2 (already generated) to a 3rd column and calculate the difference between N1 and N2 using above formula?我的问题是如何将 N1 和 N2(已生成)的值传递给第三列并使用上述公式计算 N1 和 N2 之间的差异?
Note: Please note that is percentage difference between 2 numbers and not the percentage change where (N2-N1) / N1 * 100 applies...注意:请注意,这是 2 个数字之间的百分比差异,而不是 (N2-N1) / N1 * 100 适用的百分比变化......
Thank you in advance for any reply...预先感谢您的任何答复...
You have a strange definition of "difference".你对“差异”有一个奇怪的定义。 For this, use a subquery:为此,请使用子查询:
SELECT CONCAT('£ ', n1) AS Total_N1,
CONCAT('£ ', n2) AS Total_N2,
100 * (N1 - N2) / (N1+N2) / 2 as diff
FROM (SELECT SUM(CASE WHEN t1.col_type = 'N1' THEN t2.qty * t1.price ELSE 0 END) as n1,
SUM(CASE WHEN t1.col_type = 'N2' THEN t2.qty * t1.price ELSE 0 END) as n2
FROM t2 INNER JOIN
t1
ON t2.col_id = t1.col_id
) t
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.