Click here to Skip to main content
15,886,806 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
hello pls i need help on my school project. I have tables try1 and try2, i want to join the two showing the income and expenditure sorted with the date accordingly from the try1 and try2

try1
         +------+-------+--------+--------+
         |  id  | date  | name   |expensis|
         +------+-------+--------+--------+
         |  1   |17/11/1|  shoe  |   200  |
         +------+-------+--------+--------+
         |  2   |17/11/2|  books |   300  |
         +------+-------+--------+--------+
         |  3   |17/11/2| T.fair |   400  |
         +------+-------+--------+--------+
try2
         +------+-------+--------+--------+
         |  id  | date  | name   | source |
         +------+-------+--------+--------+
         |  1   |17/11/1|  Dad   |  1000  |
         +------+-------+--------+--------+
         |  2   |17/11/2| uncle  |        |
         +------+-------+--------+--------+
         |  3   |17/11/4|  Bro   | 150    |
         +------+-------+--------+--------+
    
    RESULT
             +-------+--------+--------+
             | date  |expensis| source |
             +-------+--------+--------+
             |17/11/1|  200   |  1000  |
             +-------+--------+--------+
             |17/11/2|  300   |        |
             +-------+--------+--------+
             |17/11/2|  400   |        |
             +-------+--------+--------+
             |17/11/4|        |  150   |
             +-------+--------+--------+


What I have tried:

SELECT u.date, b.amount, h.amount
FROM
  (SELECT Date FROM try1 UNION SELECT Date FROM try2) u
  RIGHT JOIN try1 b ON u.Date=b.Date
 RIGHT JOIN try2 h ON u.Date=h.Date
Posted
Updated 29-Nov-17 6:11am
Comments
José Amílcar Casimiro 25-Nov-17 6:59am    
select try2.date, try1.expensis, try2.source
from try1
right join try2
on try1.date = try2.date

1 solution

José Amílcar Ferreira Casimiro (@jafcasimiro) has given you one solution.

Here is a good CodeProject article for you to understand joins better
Visual Representation of SQL Joins[^]

And here is another one to help you understand how subqueries work:
SQL Server: Subqueries[^]

A couple of other points ...

a) you try to query on columns b.amount and h.amount but neither table has such a column name.

b) Avoid using "Reserved Words" for column names - for example date and name. If you do use them then remember to surround them with square brackets to distinguish between the column name and the type (or other reserved word).
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900