0

I have 2 tables . each table has two columns.

DocumentNumber      price

I want to use a query to show same documentnumber and count of ducumentnumber in each table. I used this code.

Select  Sheet.DocumentNumber , Sheet2.DocumentNumber ,Count(sheet.documentnumber) , Count(sheet2.documentnumber) 

        From Sheet,Sheet2
        where sheet.DocumentNumber=sheet2.DocumentNumber

        group by sheet.DocumentNumber , Sheet2.DocumentNumber

but instead of counting document numbers it shows me the Cartesian of two column.

And I want to show price of each table and (sheet.price) minus (sheet2.price)

please complete my query.

1 Answer 1

1

You should use proper join syntax. In particular, for this, you should use full outer join because it is possible that a document has no records in one or the other table.

Second, because you don't want to count duplicates, you need to count something. The following assumes that there is an id column (of some sort) in each table:

Select  coalesce(s.DocumentNumber, s2.DocumentNumber) as DocumentNumber,
        Count(distinct s.id), Count(distinct s2.id)
From Sheet s full outer join
     Sheet2 s2
     on s.DocumentNumber = s2.DocumentNumber
 group by  coalesce(s.DocumentNumber, s2.DocumentNumber);

If you don't have an id column, or if your database does not support full outer join, the following will also work:

select DocumentNumber, max(cnt_s) as cnt_s, max(cnt_s2) as cnt_s2
from ((select DocumentNumber, count(*) as cnt_s, 0 as cnt_s2
       from Sheet s
       group by DocumentNumber
      ) union all
      (select DocumentNumber, 0, count(*) as cnt_s2
       from Sheet2 s2
       group by DocumentNumber
      )
     ) t
group by DocumentNumber;

EDIT:

The union all approach is actually better for the price:

select DocumentNumber, max(cnt_s) as cnt_s, max(cnt_s2) as cnt_s2,
       max(price_s) - max(price_s2)
from ((select DocumentNumber, count(*) as cnt_s, 0 as cnt_s2,
              sum(price) as price_s, 0 as price_s2
       from Sheet s
       group by DocumentNumber
      ) union all
      (select DocumentNumber, 0, count(*) as cnt_s2,
              0, sum(price) as price_s2
       from Sheet2 s2
       group by DocumentNumber
      )
     ) t
group by DocumentNumber;

Note: This version treats a missing price as 0. You might want to replace the 0 with NULL for that situation.

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you Gordon. All queries you showed ,e are working. I used the 3rd one. it's awesome. but in 3rd one I want to show the price of first sheet and price of second sheet. and then the minus between price1 and price2

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.