【问题标题】:Percentage calculus based on multiple tables in sqlsql中基于多表的百分比演算
【发布时间】:2020-05-21 13:40:30
【问题描述】:

我在 sql 中有两个表,我需要创建另一个表来执行基于另外两个表的计算。

第一个是每个广告单元的收入总和,表名是 ad_unit_table

SELECT
    d.`Date`,
    'App' as `Partner`,
    d.`Ad Unit`,
    sum(d.`Revenue`) as `Revenue`
from
    `d_master` as d
group by
    `Ad Unit`, `Date`

另一个表包含所有广告单元的收入总和,表名为 sum_revenue

SELECT
    `Date`,
    `Partner`
    `Ad Unit`,
    sum(`Revenue`) as `Sum Revenue`
from
    `ad_unit_table`
group by
    `Date`

现在我必须找出每个广告单元的收入百分比。所以公式是 (Ad Unit Rev / Sum Rev) * 100。我的代码目前如下所示:

SELECT
    ad.`Date`,
    ad.`Partner`,
    ad.`Ad Unit`,
   (ad.`Revenue` / s.`Sum Revenue`) * 100 as `Percentage`
FROM
    `ad_unit_table` as ad
    LEFT JOIN `sum_revenue` as s ON ad.`Partner`
GROUP BY
    `Date`,
    `Ad Unit`

它给了我所有的 NULLS。我将不胜感激任何帮助。谢谢!

【问题讨论】:

  • 您的第二个查询没有意义。 select 中有未聚合的列。
  • 不幸的是(SQL 初学者不知道)如果在 ONLY_FULL_GROUP_BY 模式关闭的情况下运行(其他 RDBMS 会正确出错),MySQL 允许这样无效的第二个查询。
  • @GordonLinoff 是否有意义 - 在总收入中,我有我正在寻找的收入。我还在 DOMO 平台上运行查询,它有自己的特点。
  • @Strawberry 您的评论无关紧要。我很乐意提供数据样本。

标签: mysql sql datatables domo


【解决方案1】:

您确定要在上次查询中执行LEFT JOIN sum_revenue as s ON ad.Partner 吗?我测试了这个构造,这创建了一个所谓的笛卡尔积。 左表的所有行都与另一个表中的所有行合并。

见:https://en.wikipedia.org/wiki/Cartesian_product

例如:

 create table testing.test_a (id INT);
 create table testing.test_b (id INT);

INSERT INTO test_a VALUES(1),(2),(3),(4);
INSERT INTO test_b VALUES(1),(2),(3),(5);

# Resulting in a cartesian product (4x4 entries)
SELECT * FROM test_a AS a LEFT JOIN test_b AS b ON a.id;

+------+------+
| id   | id   |
+------+------+
|    1 |    1 |
|    2 |    1 |
|    3 |    1 |
|    4 |    1 |
|    1 |    2 |
|    2 |    2 |
|    3 |    2 |
|    4 |    2 |
|    1 |    3 |
|    2 |    3 |
|    3 |    3 |
|    4 |    3 |
|    1 |    5 |
|    2 |    5 |
|    3 |    5 |
|    4 |    5 |
+------+------+

# Correctly LEFT joining test_a and test_b would be:
SELECT a.id, b.id FROM test_a AS a LEFT JOIN test_b AS b ON a.id = b.id

# Or use the USING clause to join on column from both tables with same name.
SELECT test_a.id, test_b.id FROM test_a LEFT JOIN test_b USING(id);

+------+------+
| id   | id   |
+------+------+
|    1 |    1 |
|    2 |    2 |
|    3 |    3 |
|    4 | NULL |
+------+------+

您确定表sum_revenue 包含ad_unit_table 中所有单位的条目吗?如果不是这种情况,由于条目不匹配,sum_revenue 中的某些值会导致 NULL 值。 如果您只想要匹配的值,请使用 INNER JOIN 而不是 LEFT JOIN

还要确保何时可以进行计算。没有一个值是NULL。使用NULL 值进行计算会得到NULL 值。

例子:

SELECT 100 / NULL;         -- Result NULL
SELECT (10 * NULL) * 100;  -- Result NULL

如果没有更多信息,例如表定义和/或示例数据,这就是我所能做的。

【讨论】:

    猜你喜欢
    • 2016-05-30
    • 1970-01-01
    • 1970-01-01
    • 2020-10-11
    • 1970-01-01
    • 1970-01-01
    • 2019-06-03
    • 1970-01-01
    • 2016-07-07
    相关资源
    最近更新 更多