【问题标题】:SQLite - Arithmetic on columns from three different tables (sum, multiply, subtract, etc..)SQLite - 对来自三个不同表的列进行算术运算(求和、乘、减等)
【发布时间】:2018-05-30 07:30:39
【问题描述】:

使用 SQLite 查询,我尝试使用不同表中的列执行算术运算,其中我将不同组中的产品价格乘以与单独表中每个组对应的百分比:

< Products Table >
Column Z  Column X Column Y
Product 1 Price 1  Delivery A
Product 2 Price 2  Delivery B
Product 3 Price 3  Delivery A
Product 4 Price 4  Delivery A
Product 5 Price 5  Delivery B
Product 6 Price 6  Delivery C

< Delivery Table >
Column O  Column P
Delivery A Warehouse A
Delivery B Warehouse A
Delivery C Warehouse B

< Warehouse Percentage Table >
Column M Column N
Warehouse A  Percentage A
Warehouse B  Percentage B

< Results Table / View >
Column E  Column F
Product 1 Total 1 (Price 1 * Percentage A)
Product 2 Total 2 (Price 2 * Percentage B
Product 3 Total 3 (Price 3 * Percentage A)
Product 4 Total 4 (Price 4 * Percentage A)
Product 5 Total 5 (Price 5 * Percentage B)
Product 6 Total 6 (Price 6 * Percentage B)

我已经设法弄清楚如何对同一个表中的列执行算术运算,从而创建一个新视图:

SELECT id,
    SUM(column_a*column_b)
    FROM table_1
    GROUP BY id

我还设法加入了三个表:

SELECT *
  FROM table_1
       INNER JOIN
       table_2 ON table_1.column_1 = table_2.column_1
       INNER JOIN
       table_3 ON table_2.column_2 = table_3.column_2;

但我不知道如何对由第三个表连接的两个不同表中的两列执行算术运算,例如:

SUM(table_1.column_1*table_3.column_2)

当我将这行代码添加到连接所有三个表的查询中时:

The SELECT statement could not be parsed. Please correct the query and retry. Details: Syntax error

我也没有办法直接将INNER JOINtable_1 转为table_3,因为它们没有对应的值,所以我必须通过table_2 加入。

【问题讨论】:

  • 你首先加入表,然后从适当的源表访问列...?
  • 你在 ON 子句中使用的那个已经...tablename.columnname
  • 是的,当然寻址列在这个地方的工作方式和其他地方一样。
  • 您为什么使用 SUM?任何表是否有一个产品的多行?

标签: mysql sql sqlite


【解决方案1】:

此解决方案非常简单,但如果您像我一样是 sql 新手,则不然:

SELECT table_1.price * table_3.percentage
       INNER JOIN
       table_2 ON table_1.column_1 = table_2.column_1
       INNER JOIN
       table_3 ON table_2.column_2 = table_3.column_2;

似乎sql中的任何算术都需要在SELECT语句中完成。

下面更复杂的算术语法让我走错了路,而实际上解决方案要简单得多:

SELECT id,
    SUM(column_a*column_b)
    FROM table_1
    GROUP BY id 

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-12-28
    • 2013-09-06
    • 1970-01-01
    • 1970-01-01
    • 2017-10-25
    • 2018-10-10
    • 2014-10-02
    相关资源
    最近更新 更多