SQL-如何基于其他列的值添加计算列

时间:2020-08-28 09:00:03

标签: sql oracle join left-join

我有两个表:T1 =供应商,T2 =附加数据。

T1供应商栏:ID,名称,代码等

值:

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

T2 Additional_data列:id,supplier_id,additional_category_name,值

值:

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

我有以下查询:

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;

这给了我所有的供应商,即使他们的附加数据中没有VAT_NUMBER:

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

如您所见,并非所有供应商都有相同的附加类别。但我有兴趣获得所有供应商及其增值税清单的清单。如果VAT_Number为空,则可以添加“ N / A”:

所需的输出:

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

请让我知道如何实现这一目标。

谢谢!

2 个答案:

答案 0 :(得分:1)

只需过滤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'

答案 1 :(得分:1)

在最终结果上,使用分组和大小写以下查询来获得所需结果。

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;