简体   繁体   English

使用联接的SQL函数中的算术

[英]Arithmetic in SQL function using Joins

I am new to SQL. 我是SQL新手。 I am trying to perform some arithmetic using an SQL function. 我正在尝试使用SQL函数执行一些算术运算。

I have three tables: 我有三个表:

Table1 表格1

Table1_ID
Table2_ID
Value 

Table2 表2

Table2_ID
Switch

Table3 表3

Table3_ID
Table1_ID
Table2_ID
X_Column

I have the contents of X_Column from Table 3 as input to start with, which will be the input to my function. 我将表3中X_Column的内容作为输入开始,这将是我函数的输入。 These are the conditions: 这些是条件:

1) Multiple Table2_ID can have the same X_Column input and not vice versa 1)多个Table2_ID可以具有相同的X_Column输入,反之亦然

2) Multiple Table1_ID can have the same Table2_ID and not vice versa 2)多个Table1_ID可以具有相同的Table2_ID,反之亦然

3) Every X_Column input has one or more Table2_IDs; 3)每个X_Column输入都有一个或多个Table2_ID; Every Table2_ID has one or more Table1_IDs 每个Table2_ID具有一个或多个Table1_ID

All I want to do is multiply and return the contents of the field Value from Table1, which has a Table1_ID, a corresponding Table2_ID, a corrsponding Table3_ID corresponding to an input X_Column, whenever a particular input X_Column is inputted. 我想要做的就是乘以并返回Table1中的Value字段的内容,每当输入特定的输入X_Column时,Table1就有一个Table1_ID,一个对应的Table2_ID,一个与输入X_Column对应的对应的Table3_ID。

I am not able to understand how to do this. 我不明白该怎么做。 I think it is possible using Joins or Views. 我认为可以使用联接或视图。 I don't have any related code to post here yet. 我没有任何相关代码可发布在这里。 Could someone please help? 有人可以帮忙吗?

I'm guessing at the column data types... 我猜在列数据类型...

Join the tables through the Table2_ID column. 通过Table2_ID列联接表。 When the rows from the different tables are joined, you can multiply the columns: Table1.Value * Table3.X_Column 连接来自不同表的行时,可以乘以以下列: Table1.Value * Table3.X_Column

-- sample tables
declare @Table1 table (Table1_ID int, Table2_ID int, Value numeric(18,2));
declare @Table2 table (Table2_ID int, Switch bit);
declare @Table3 table (Table3_ID int, Table1_ID int, Table2_ID int, X_Column numeric(18,2));

-- sample data
insert @Table1 values(100, 200, 5.00);
insert @Table1 values(100, 201, 10.00);
insert @Table2 values(200, 0);
insert @Table2 values(201, 1);
insert @Table3 values(300, 100, 200, 2.0);
insert @Table3 values(300, 100, 201, 2.5);

declare @X_Column numeric(18,2);
set @X_Column = 2.0;

select
    t1.Value * t3.X_Column
from @Table1 t1
join @Table2 t2 on t2.Table2_ID = t1.Table2_ID
join @Table3 t3 on t3.Table2_ID = t2.Table2_ID
where t3.X_Column = @X_Column

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM