简体   繁体   English

SQL 查询查看 3 列并且仅拉取非空白值

[英]SQL Query That Looks At 3 Columns And Only Pulls The Non Blank Value

I am looking for a way to pull all invoices from a table with the tracking number for that invoice.我正在寻找一种方法从带有该发票跟踪号的表格中提取所有发票。 For example:例如:

SELECT Invoice, FedEx, UPS, DHL from shipfile

would show all invoices and all tracking numbers.将显示所有发票和所有跟踪号。 If it was shipped FedEx, the tracking number will be in the FedEx column.如果它是由 FedEx 运送的,则跟踪号将在 FedEx 列中。 Same for the others.其他人也一样。 I want to be able to pull out the Invoice and then 1 other "Tracking" column that will display either the FedEx, UPS or DHL result (which ever one contains the tracking number).我希望能够拉出发票,然后再拉出 1 个其他“跟踪”列,该列将显示 FedEx、UPS 或 DHL 结果(其中任何一个都包含跟踪号)。 So if there is a FedEx tracking number, UPS and DHL will be blank, so I'd want to see the Invoice and the FedEx tracking number.因此,如果有 FedEx 跟踪号,UPS 和 DHL 将是空白的,所以我想查看 Invoice 和 FedEx 跟踪号。 And same thing if it has UPS tracking, FedEx and DHL will be blank so I want to only see the UPS result.同样,如果它有 UPS 跟踪,FedEx 和 DHL 将是空白的,所以我只想看到 UPS 结果。

Before:前:

Invoice  FedEx   UPS   DHL


1        F123    

2                U321

3                      D746

After:后:

Invoice    Tracking

1          F123

2          U321

3          D746

Use coalesce() :使用coalesce()

select invoice, coalesce(fedex, ups, dhl) as tracking_number
from shipfile;

Assuming that these "blank" values are actually NULL , we can use COALESCE here:假设这些“空白”值实际上是NULL ,我们可以在这里使用COALESCE

SELECT Invoice, COALESCE(FedEx, UPS, DHL) AS Tracking
FROM shipfile;

If the blank values are really empty string, then use the scalar GREATEST function instead:如果空白值确实是空字符串,则使用标量GREATEST function 代替:

SELECT Invoice, GREATEST(FedEx, UPS, DHL) AS Tracking
FROM shipfile;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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