Ankith
Ankith

Reputation: 157

Self Join + Left Join in Sql Server

I have a table that can store different messurement values with type as associated column to store measurement type.

following Is a sample table with data

enter image description here

I am able to self join the table to get ht and wt values based on date. My requirement is, I also need wt values of all dates even if ht for that date is not there in the table.

Sample result

enter image description here

EDIT: I tried below query but it is returning only first row.

SELECT 
  ta.uid, ta.value as 'wt', lta.value as 'ht', ta.date,ta.id as lftid, lta.id as rtid FROM 
  [test].[dbo].[tbl2] ta
     LEFT JOIN [test].[dbo].[tbl2] Lta 
        ON ta.[date] = Lta.[date]
       AND ta.[uid] = 11 WHERE 
      ta.type = 'wt'
  AND Lta.type ='ht'

Upvotes: 0

Views: 2174

Answers (2)

Jayvee
Jayvee

Reputation: 10875

With just a few changes to your query it should work:

SELECT 
  ta.uid, ta.value as 'wt', lta.value as 'ht', ta.date,ta.id as lftid, lta.id as rtid FROM 
  [test].[dbo].[tbl2] ta
     LEFT JOIN [test].[dbo].[tbl2] Lta 
        ON ta.[date] = Lta.[date]
       AND ta.[uid] = 11  and ta.type<>Lta.type
       WHERE 
      ta.type = 'wt'
  AND isnull(Lta.type,'ht') ='ht'

Upvotes: 1

Zohar Peled
Zohar Peled

Reputation: 82524

The fact that you are refering to the right alias in the where clause effectively changes your left join to an inner join.
Read this answer to find out why.
To avoid that, move the conditions in the where clause to the on clause:

SELECT ta.uid, 
       ta.value as 'wt', 
       lta.value as 'ht', 
       ta.date,
       ta.id as lftid, 
       lta.id as rtid 
FROM [test].[dbo].[tbl2] ta
LEFT JOIN [test].[dbo].[tbl2] Lta 
ON ta.[date] = Lta.[date]
AND ta.type = 'wt'
AND Lta.type ='ht'           
WHERE ta.[uid] = 11 

Upvotes: 0

Related Questions