A Coder
A Coder

Reputation: 3046

Separate column based on condition in same table in SQL

I'm having a result set from a table in which I have to split a specific value and display in another column(user defined) based on a condition.

//Query

    SELECT wtcCommentId, wtcTransactionId, wtcTaskId,  wtcUserLogin,
     wtcCommentDateTime, wtcCommentText
    FROM   dbo.tblWorkflowTransactionComments (NOLOCK)
    WHERE  wtcTransactionId = 141248

The output for the above query will be some 10 rows.

In the above query I need to separate the wtcCommentText column if the wtcTaskId for that result is 0. So if the wtcTaskId is 0 the wtcCommenttext value should be displayed in a separate column(transcommenttext) and for others it should be displaying in the same column(wtcCommentText). So that I can make a split between the comments based on the taskId.

How can I achieve this?

Upvotes: 0

Views: 3852

Answers (1)

Damien_The_Unbeliever
Damien_The_Unbeliever

Reputation: 239684

I'm not sure it really makes sense, but okay, I'm game for a laugh:

SELECT wtcCommentId, wtcTransactionId, wtcTaskId,  wtcUserLogin,
 wtcCommentDateTime,
 CASE WHEN wtcTaskId!=0 THEN wtcCommentText END as wtcCommentText,
 CASE WHEN wtcTaskId=0 THEN wtcCommentText END as transcommenttext
FROM   dbo.tblWorkflowTransactionComments (NOLOCK)
WHERE  wtcTransactionId = 141248

It seems like the kind of trivial reformatting that would be better done in a front end or report generator though.

Upvotes: 4

Related Questions