Quantcast
Channel: Transact-SQL forum
Viewing all articles
Browse latest Browse all 23857

Finding discrepancies in two tables is SQL Server for two fields that have the same values an ids

$
0
0

Hi,

I have two tables namely table1, and table2 that both have amount and id.  The id is the same in both fields and the sum(amt)in both tables must be the same for the same id else there is  discrepancies   in either record that can be checked by id.

Structures:

CREATE TABLE dbo.Table1
    (
    pid int NOT NULL IDENTITY (1, 1),
    amt numeric(18, 5) NULL,
    id int NULL
    )  ON [PRIMARY]


CREATE TABLE dbo.Table2
    (
    pid int NOT NULL IDENTITY (1, 1),
    amt numeric(18, 5) NULL,
    id int NULL
    )  ON [PRIMARY]

insert into dbo.Table1(amt,id) values (20,1)

insert into table1(amt,id) values (90,1)

insert into table1(amt,id) values (98,10)

insert into table1(amt,id) values (54,10)

insert into dbo.Table2(amt,id) values (20,1)

insert into table2(amt,id) values (90,1)

insert into table2(amt,id) values (98,10)

insert into table2(amt,id) values (54,10)

I use the query like:

SELECT Sum1,Sum2,t1.id FROM (select SUM(amt) as Sum1,id from table1 Group by id) t1 cross join
(select SUM(amt) Sum2,id FROM table2  group by ID) t2

but the result is not what I want. I want the result to be:

Sum1            Sum2       id 

110                 110        1

152                 152        10

but the result is:

Sum1                   Sum2    id
110.00000    110.00000    1
110.00000    152.00000    1
152.00000    110.00000    10
152.00000    152.00000    10

which repeat itself

This will help me find out which table have recorded wrong values because both records should have same value. Note that id is the id of another document!


Mike


Viewing all articles
Browse latest Browse all 23857

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>