SQL select statement using same column twice

Ken King 1 Reputation point
2020-05-29T01:02:52.523+00:00

I have a simple select statement from one table that lists the same numeric column (TRANAMT) twice. If the number is positive (>0) I want it to show in the first reference of TRANAMT. If the number is negative (<0) I want it to should in the next reference of TRANAMT. Ideally if the number is positive it will show on the first reference and the second will display 0 or null. If negative the first reference shows 0 or null and the second reference shows the negative number.

select FNAME, LNAME, TRANAMT, TRANAMT
from CMLEDG

Please let me know if this is possible.
Thanks Ken

Azure SQL Database
0 comments No comments
{count} votes

2 answers

Sort by: Most helpful
  1. Vaibhav Chaudhari 38,576 Reputation points
    2020-05-29T13:02:34.497+00:00

    Try something below. See if it works

    SELECT FNAME
        ,LNAME
        ,CASE 
            WHEN TRANAMT > 0
                THEN TRANAMT
            ELSE NULL
            END TRANAMT_Positive
        ,CASE 
            WHEN TRANAMT < 0
                THEN TRANAMT
            ELSE NULL
            END TRANAMT_Negative
        ,TRANAMT
    FROM CMLEDG
    

    If the response helped, do "Accept Answer" and upvote it - Vaibhav

    1 person found this answer helpful.
    0 comments No comments

  2. Leon Laude 85,651 Reputation points
    2020-05-29T01:06:28.687+00:00

    Hi,

    Q&A currently supports the products listed over here https://learn.microsoft.com/en-us/answers/products (more to be added later on).

    You can reach the experts in the dedicated SQL Server forum over here:
    https://social.technet.microsoft.com/Forums/en-US/home?category=sqlserver

    (Please don't forget to accept helpful replies as answer)

    Best regards,
    Leon

    0 comments No comments