3

I want below output through SQL server.

TABLE A

| Id   |   Name   | 2016 | 2017 |  
 - - - - - - - - -  - - - - - - - 
| 1    |  ABCDEFG |      |      |
| 2    |  XYZLMON |      |      |

TABLE B

| Id   | Value | Year |  
 - - - - - - - - - - -
| 1    |  F    | 2016 |
| 1    |  G    | 2017 |

OUTPUT

| Id   |   Name   | 2016 | 2017 |  
 - - - - - - - - -  - - - - - - - 
| 1    |  ABCDEFG |  F   |  G   |
| 2    |  XYZLMON |      |      |

3 Answers 3

1

You can do this with two joins:

select a.*, b2016.value as val2016, b2017.value as val2017
from a left join
     b b2016
     on a.id = b.id and b.year = 2016 left join
     b b2017
     on a.id = b.id and b.year = 2017;
Sign up to request clarification or add additional context in comments.

1 Comment

giving an error : The multi-part identifier could not be bound.
1

You can join these tables and pivot as below:

Select * 
from (
    Select 
        a.Id, 
        a.[Name], 
        b.[Value], 
        b.[year] 
    from tablea a
    left join tableb b on a.Id = b.id
) a
pivot (
    max([Value]) 
    for [Year] in ([2016],[2017]) 
) p

Comments

0

Try this:

SELECT 
    tbla.id as Id, 
    tbla.name as Name, 
    (SELECT 
        value 
     FROM tblb 
     WHERE tblb.Id = tbla.id 
     AND tblb.Year ='2016') as 2016, 
     (SELECT 
          value 
      FROM tblb 
      WHERE tblb.Id = tbla.id 
      AND tblb.Year ='2017') as 2017 
FROM tbla;

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.