Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations gkittelson on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

using a created column name in subsequent case statement

Status
Not open for further replies.

swhitten

Technical User
Sep 3, 2002
191
US
I am writing a select statement to use in a view. The first column of data I need is retrieved with the first case statement below; I call that column TxnCode. Then I need to write data to a second column that depends on the TxnCode returned in the first column. The script below tells me 'invalid column mame 'TxnCode''. It is not recognizing the alias from the first case statement.

Is there an easy way to re-write this so I can use the TxnCode in the second case statement? Thanks.


SELECT
CASE
WHEN doctype = 6 THEN 'SPPC'
WHEN doctype = 4 THEN 'RPPC'
WHEN doctype = 1 AND trxqty < 1 THEN 'ANPC'
WHEN doctype = 1 AND trxqty > 1 THEN 'APPC'
ELSE 'HELP' END AS TxnCode,

CASE TxnCode
WHEN 'RPPC' THEN 'I'
WHEN 'APPC' THEN 'I'
WHEN 'RNPC' then ''
WHEN 'SPPC' THEN ''
WHEN 'ANPC' THEN ''
ELSE 'HELP' END as NewColumn

FROM dbo.IV30300
 
Code:
SELECT TxnCode
     , CASE WHEN TxnCode IN ('RPPC','APPC') 
            THEN 'I' 
            WHEN TxnCode IN ('RNPC','SPPC','ANPC') 
            THEN '' 
            ELSE 'HELP' END as NewColumn
  FROM ( SELECT CASE WHEN doctype = 6                
                     THEN 'SPPC'                     
                     WHEN doctype = 4                
                     THEN 'RPPC'                     
                     WHEN doctype = 1 AND trxqty < 1 
                     THEN 'ANPC'                     
                     WHEN doctype = 1 AND trxqty > 1 
                     THEN 'APPC'                     
                     ELSE 'HELP' END AS TxnCode 
           FROM dbo.IV30300 ) AS t

r937.com | rudy.ca
Buy my new book Simply SQL from Amazon
 
Okay, this is getting me closer. Now I need to add other fields from IV30300 as well as additional created columns to my select statement. Not sure where to put these additional items in the new select statement. I need to add fields like:

'12345' AS PartnerID,
CONVERT(varchar, GETDATE(), 112) + 'T000000' AS EffDate,
ITEMNMBR AS ProductNum,
CASE WHEN trxqty > 0 THEN TrxQty ELSE (TrxQty * - 1) END AS TxnQty

Where do I put those in the revised select statement above? Thanks again!
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top