I have two tables as below
Table 1 ----------------------------------- UserID | UserName | Age | Salary ----------------------------------- 1 | foo | 22 | 33000 -----------------------------------
Table 2 ------------------------------------------------ UserID | Age | Salary | CreatedDate ------------------------------------------------ 1 | NULL | 35000 | 2015-01-01 ------------------------------------------------ 1 | 28 | NULL | 2015-02-01 ------------------------------------------------ 1 | NULL | 28000 | 2015-03-01 ------------------------------------------------
I need the result like this.
Result ----------------------------------- UserID | UserName | Age | Salary ----------------------------------- 1 | foo | 28 | 28000 -----------------------------------
This is just an example. In my real project I have around 6 columns like Age and Salary in above tables.
In table 2 , each record will have only have one value i.e if Age has value then Salary will be NULL and viceversa.
UPDATE :
Table 2 has CreatedDate Column. So i want to get latest "NOTNULL" CELL Value instead of maximum value.
The table on the "one" side of the "one-to-many" relationship should have a primary key column. The other table should have a foreign-key defined pointing to the primary key on the first table. To return results from both tables you'd add an INNER JOIN clause to join both tables.
SQL LEFT JOIN examples Each location belongs to one and only one country while each country can have zero or more locations. The relationship between the countries and locations tables is one-to-many.
Four types of joins: left, right, inner, and outer.
A one-to-many relationship is created if only one of the related columns is a primary key or has a unique constraint. In the relationship window in Access, the primary key side of a one-to-many relationship is denoted by a number 1. The foreign key side of a relationship is denoted by an infinity symbol.
You can get this done using a simple MAX()
and GROUP BY
:
select t1.userid,t1.username, MAX(t2.Age) as Age, MAX(t2.Salary) as Salary
from table1 t1 join
table2 t2 on t1.userid=t2.userid
group by t1.userid,t1.username
Result:
userid username Age Salary
--------------------------------
1 foo 28 35000
Sample result in SQL Fiddle
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With