比较两个表中的值并计算它们的差异

Posted

技术标签:

【中文标题】比较两个表中的值并计算它们的差异【英文标题】:Compare values in two tables and calculate the difference of them 【发布时间】:2020-07-25 03:05:41 【问题描述】:

DB-Fiddle

/* Table Sales */
CREATE TABLE sales (
    id int auto_increment primary key,
    product VARCHAR(255),
    KPI VARCHAR(255),
    sales_volume INT
);

INSERT INTO sales
(product, KPI, sales_volume)
VALUES 
("Product A", "sold", "500"),
("Product A", "sold", "300"),
("Product B", "sold", "200"),
("Product C", "sold", "300"),
("Product D", "sold", "900");


/* Table Logistics */
CREATE TABLE logistics (
    id int auto_increment primary key,
    product VARCHAR(255),
    KPI VARCHAR(255),
    quantity INT
);

INSERT INTO logistics
(product, KPI, quantity)
VALUES 
("Product A", "outbound", "800"),
("Product B", "outbound", "100"),
("Product B", "outbound", "400"),
("Product C", "outbound", "250"),
("Product D", "outbound", "900");

预期结果:

product         value_in_sales      value_in_logistics      differnce_of_values
Product A        800                     800                       0
Product B        200                     500                       300
Product C        300                     250                       -50
Product D        900                     900                       0

在上面的示例中,我有两个名为saleslogistics 的表。 我的目标是将sales 表中KPI soldsales_volumelogistics 表中KPI outboundquantity 进行比较。

我尝试使用UNION ALL,但它仅将两个表的值排序在彼此下方,并没有像预期的结果那样比较它们。

SELECT
product,
KPI,
SUM(sales_volume)
FROM sales
GROUP BY 1

UNION ALL

SELECT
product,
KPI,
SUM(quantity)
FROM logistics
GROUP BY 1

我需要对查询进行哪些更改才能获得预期结果?

【问题讨论】:

【参考方案1】:

使用子查询并进行进一步聚合:

SELECT Product, SUM(logistics),  SUM(Sales),
       SUM(logistics) - SUM(Sales)
FROM (SELECT product, 0 AS logistics, SUM(sales_volume) AS Sales
      FROM sales
      WHERE KPI = 'sold'
      GROUP BY Product
      UNION ALL
      SELECT product, SUM(quantity), 0 
      FROM logistics
      WHERE KPI = 'outbound'
      GROUP BY Product
     ) t
GROUP BY Product;

【讨论】:

dbfiddle.uk/… 仅用于我自己的文档:dbfiddle.uk/…【参考方案2】:

你可以做union all然后再次聚合:

SELECT product, SUM(sales) as sales, SUM(logistics) as logistics,
       (SUM(logistics) - SUM(sales)) as diff
FROM ((SELECT product, SUM(sales_volume) as sales, 0 as logistics
       FROM sales
       WHERE KPI = 'sold'
       GROUP BY product
      ) UNION ALL
      (SELECT product, 0, SUM(quantity)
       FROM logistics
       WHERE KPI = 'outbound'
       GROUP BY product
      )
     ) p
GROUP BY product;

即使两个表没有完全相同的产品,这种方法也有效。

【讨论】:

以上是关于比较两个表中的值并计算它们的差异的主要内容,如果未能解决你的问题,请参考以下文章

Oracle SQL:比较 2 列中的所有值并交换它们

计算两个不相邻行之间的差异

比较一个结构的两个值并在 UITableView swift 4.0 中获取额外的单元格

sql比对两个表中的差异数据比较的sql语句

是否可以比较一行中的两个值并获取所需的值,但这两个值都与写入的正则表达式匹配

比较数组中的值计算它们并合并表中的行