简体   繁体   中英

Adding columns in result in SQL from one column

First time here so I didn't see a question like this so I hope you can help me.

I am attempting to add 2 columns to a query result.

  • If aa.actionid = '123' , return a result in a column called test1 .

  • If aa.actionid = '5' , then create a column called this to put the price per ton in that column called either test 1 or test 2

This is what I have so far. I am not really sure if this is right:

SELECT CO.INVOICE_PREFIX
  ,C.CUSTOMER_NAME 
  ,S.SITE_NAME 
  ,W.DESCRIPTION
  ,AA.PER_TON_PRICE
  ,AA.ACTION_ID
  ,AA.APPLICABLE_ACTION_ID 
  ,OI.VALID_UNTIL 
  ,CON.END_DATE 
  ,CC.DESCRIPTION 
  ,(case when aa.actionid = '123' then aa.per_ton_price Test1
  ,(case when aa.actionid = '5' then) aa.per_ton_price test2

FROM CUSTOMER C
JOIN SITE S ON C.CUSTOMER_ID = S.CUSTOMER_ID
JOIN CONTRACT CON ON C.CUSTOMER_ID = CON.CUSTOMER_ID
JOIN SITE_ORDER SO ON SO.SITE_ID = S.SITE_ID
JOIN COMPANY_OUTLET CO ON SO.COMPANY_OUTLET_ID = CO.COMPANY_OUTLET_ID 
JOIN ORDER_ITEM OI ON OI.ORDER_ID = SO.SITE_ORDER_ID
JOIN PRODUCT P ON OI.PRODUCT_ID = P.PRODUCT_ID
JOIN APPLICABLE_ACTION AA ON AA.ORDER_ITEM_ID = OI.ORDER_ITEM_ID
JOIN COMPETITIVE_CONDITION CC ON CC.COMPETITIVE_CONDITION_ID = OI.COMPETITIVE_CONDITION_ID
LEFT JOIN WASTE W ON W.WASTE_ID = AA.WASTE_ID
JOIN ACTION A ON AA.ACTION_ID = A.ACTION_ID
WHERE AA.ACTION_ID IN ('123','5')
AND P.PRODUCT_ID='2'
AND OI.VALID_UNTIL >= GETDATE()

You will always need to return both columns for all rows. What you can do is map the 'unused' column (dependent on the row data) to a default value, such as null, eg:

 ,case when aa.actionid = '123' then aa.per_ton_price else null end Test1
 ,case when aa.actionid = '5' then aa.per_ton_price else null end test2

The database is only going to return a TABLE, so if you think about the concept of a Table, could one row have different amount of columns than the others? Probably not. So what you really want to be doing is set the particular column's value to null instead of trying to not output that column at all.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM