1

I have this SQL:

SELECT sets.set_id, responses.Question_Id, replies.reply_text, responses.Response
FROM response_sets AS sets
INNER JOIN responses AS responses ON sets.set_id = responses.set_id
INNER JOIN replies AS replies ON replies.reply_id = responses.reply_id
WHERE sets.Sctn_Id_Code IN ('668283', '664524')

A partial result:

enter image description here

I want to replace the reply_text and response columns with one column that will have the value of the response if it isn't null and the reply text value otherwise. I'm not sure if this can be done with a case statement, at least nothing I've dug up leads me to think that I can. Am I incorrect in assuming this?

tshepang
  • 12,111
  • 21
  • 91
  • 136
Michael Robinson
  • 1,106
  • 3
  • 13
  • 40

3 Answers3

0

You could use a case statement, but COALESCE would be easier:

Select sets.set_id, responses.Question_Id, COALESCE(responses.Response, replies.reply_text)
From response_sets as sets
inner join responses as responses on sets.set_id = responses.set_id
inner join replies as replies on replies.reply_id = responses.reply_id
where sets.Sctn_Id_Code in ('668283', '664524')

COALESCE allows you to list two or more expressions, and takes the first one that isn't null.

Jeff Rosenberg
  • 3,522
  • 1
  • 18
  • 38
0

Yes, ISNULL(responses.Response, replies.reply_text) or COALESCE also works. Please see this post for more information and examples. This article dives deeper into ISNULL vs COALESCE.

Community
  • 1
  • 1
SQLMason
  • 3,275
  • 1
  • 30
  • 40
0

This is from an Oracle select statement, but if it works in Oracle, it's possible it will also work in SQL Server (with some syntax changes):

, (case when bseg1.start_dt is null then bseg2.start_dt else bseg1.start_dt end) bseg_startdt

This is selecting the second start date when the first is null.

Specific SQL Server answers will be a better option, of course.

thursdaysgeek
  • 7,696
  • 20
  • 78
  • 115