简体   繁体   中英

SQL - How to add a calculated column based on values from other columns

I have two tables: T1 = Suppliers, T2 = Additional_data.

T1 Suppliers columns: id, name, code, etc.

Values:

123 | Supplier1 | 10000 
124 | Supplier2 | 10001
125 | Supplier3 | 10002

T2 Additional_data columns: id, supplier_id, additional_category_name, value

Values:

334 | Supplier1 | Street | Flower Street
335 | Supplier1 | Bank | National Bank
336 | Supplier2 | Street | Different Street
337 | Supplier2 | Bank | National Country Bank
338 | Supplier2 | VAT_NUMBER | DE23231231
339 | Supplier3 |Street | This Street
340 | Supplier3 |Leader | John M
341 | Supplier3 | VAT_NUMBER | DE12312311

I have the following query:

SELECT s.Code, s.Name, ad.additional_category_name as ADDITIONAL_CATEGORIES, ad.value
FROM ADM_SUPPLIER s LEFT OUTER JOIN
     ADM_SUPPLIER_ADDITIONAL_DATA ad
     on s.ID = ad.supplier_id;

This gives me all of the suppliers, even if they don't have a VAT_NUMBER in additional_data:

CODE  | NAME      | ADDITIONAL_CATEGORIES | VALUE
10000   Supplier1   Street                  Flower Street
10000   Supplier1   Bank                    National Bank
10001   Supplier2   Street                  Different Street
10001   Supplier2   Bank                    National Country Bank
10001   Supplier2   VAT_NUMBER              DE23231231
10002   Supplier3   Street                  This Street
10002   Supplier3   Leader                  John M
10002   Supplier3   VAT_NUMBER              DE12312311

As you can see, not all suppliers have the same additional categories. But I am interested in getting a list of all the suppliers and their VAT_NUMBER. If VAT_Number is empty, then 'N/A' can be added:

Desired output:

CODE  | NAME      | VAT_NUMBER                  
10000   Supplier1   N/A
10001   Supplier2   DE23231231
10002   Supplier3   DE12312311

Please let me know how to achieve this.

Thank you!

Just filter the left join :

select s.code, s.name, coalesce(ad.value, 'N/A') as vat_number
from adm_supplier s 
left outer join adm_supplier_additional_data ad 
    on  ad.supplier_id = s.id 
    and ad.additional_category_name = 'VAT_NUMBER'

On your final result use the below query using group by and case to get the desired result.

Demo

SELECT  CODE, NAME, 
COALESCE(MAX(CASE WHEN ADDITIONAL_CATEGORIES = 'VAT_NUMBER' THEN VALUE END), 'N/A') AS VALUE 
FROM Table1 A GROUP BY CODE, NAME;

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