question

kpolomon avatar image
kpolomon asked

Case Statement

Hello, I have two tables and I would like to create table 3 with all records from table 1 and a field from table 2. In table 1, I have the following columns (Number, item, year and amount). In table 2 I have (number, owner). +------------------------------------------------------------------------+ | Number Item Year Amount Number Owner | +------------------------------------------------------------------------+ | 123 Corn 2001 200 456 Cute farms | | 345 apple 2000 105 789 PT farms | | 567 orange 2001 50 123 KP farms | | 456 corn 2000 220 345 Jelly farms | +------------------------------------------------------------------------+ I want to create a table with all columns from table 1 with an "Owner" column from table 2 populated with data where item = corn. Hope this make sense Thanks
case-statementleft joininto
10 |1200

Up to 2 attachments (including images) can be used with a maximum of 512.0 KiB each and 1.0 MiB total.

1 Answer

·
JohnM avatar image
JohnM answered
If I understand it correctly, something like this would work: SELECT t1.Number, t1.Item, t1.Year, t1.Amount, CASE t1.item WHEN 'corn' THEN T2.Owner ELSE NULL END as 'Owner' INTO dbo.table3 FROM dbo.table1 t1 LEFT JOIN dbo.table2 t2 on t1.number = t2.number WHERE t1.item = 'corn' GO EDIT: I've updated the code to reflect a CASE statement that should work. Note that I haven't tested it. This is assuming that table3 doesn't yet exist. Hope that helps!
3 comments
10 |1200

Up to 2 attachments (including images) can be used with a maximum of 512.0 KiB each and 1.0 MiB total.

kpolomon avatar image kpolomon commented ·
Thank you.. When I include the "where" clause, it returns only two records however, I need all 4 records. Basically column "Owner" should have Corn and False(Null) as variables..
0 Likes 0 ·
JohnM avatar image JohnM commented ·
I've updated my code block to include a CASE statement that should give you what you need.
0 Likes 0 ·
JohnM avatar image JohnM commented ·
And the LEFT join.
0 Likes 0 ·

Write an Answer

Hint: Notify or tag a user in this post by typing @username.

Up to 2 attachments (including images) can be used with a maximum of 512.0 KiB each and 1.0 MiB total.