SQL中的函数用于区分来自2个不同表的值,并将值放到第三个表中

时间:2017-08-24 12:17:48

标签: c# sql

我有三个表(table1,table2,table3)。

在table1中我有不同的值(其中一些是相同的,但没关系),在table2中我也有不同的值(其中一些是相同的,但没关系)。

现在我要创建一个函数,该函数将对table1的相同值求和,并对table2中的值求和,并在相同值之间进行差异,并将该值插入table3的特定列中。

表1

Option Explicit
Public Sub FindTestValues()
    Dim Destination As Worksheet, Source As Worksheet
    Dim TestColumn As Long
    Dim FirstAddress As String, FindValue As String
    Dim c As Range

    ' Set source and destination worksheets
    Set Source = ThisWorkbook.Sheets("Source")
    Set Destination = ThisWorkbook.Sheets("Destination")

    ' Column that contains 'Test' value
    TestColumn = 2
    ' Set what you want to find to variable
    FindValue = "Text"

    Set c = Source.Columns(TestColumn).Find(what:=FindValue, LookAt:=xlWhole)

    If Not c Is Nothing Then
        Do
            With Destination
                c.EntireRow.Cut Destination:=.Cells(.Cells(.Rows.Count, TestColumn).End(xlUp).Row, 1).Offset(1, 0)
            End With
            Set c = Source.Columns(TestColumn).FindNext
        Loop Until c Is Nothing
    End If
End Sub

表2

KodikosBarcode  total
1                14
2                18

table3 应该是这样的

KodikosBarcode  total
1                 1
2                 2

有人可以帮忙吗?

然后table3将有 的表3: KodikosBarcode总计 1 13 2 16 3 1

2 个答案:

答案 0 :(得分:0)

喜欢这个? (如果是MSSQL)但希望你能得到这个想法......

ERROR: (gcloud.beta.sql.connect) HTTPError 403: The client is not authorized to make this request.

要更新你会做类似的事情;

INSERT Table3
(SomeColumn)
SELECT 
(SELECT Sum(SomeColumnFromTable1) FROM Table1) - 
(SELECT Sum(SomeColumnFromTable2) FROM Table2)

答案 1 :(得分:0)

for SQL Server:

insert into table 3
    (
        KodikosBarcode
        , Diff_Value
    )
select
    t1.KodikosBarcode
    t1.total - t2.total
from 
    table1 as t1
        inner join table2 as t2
            on t2.KodikosBarcode = t1.KodikosBarcode

这假设您只希望两个表中条形码存在的行之间存在差异。

如果您正在对目标表中的现有行进行更新,则可以使用:

update t3 set
    t3.total = t1.total - t2.total
from table3 as t3
    inner join table1 as t1
        on t1.KodikosBarcode = t3.KodikosBarcode
    inner join table2 as t2
        on t2.KodikosBarcode = t3.KodikosBarcode