简体   繁体   English

将一列置于另一列之上

[英]Prioritize one column over another

DB-Fiddle 数据库小提琴

CREATE TABLE logistics (
    id int primary key,
    campaign VARCHAR(255),
    quantity_offered VARCHAR(255),
    quantity_ordered VARCHAR(255), 
    quantity_delivered VARCHAR(255),
    quantity_recorded VARCHAR(255),
    quantity_completed VARCHAR(255)
);

INSERT INTO logistics
(id, campaign,
quantity_offered, quantity_ordered, quantity_delivered, 
quantity_recorded, quantity_completed
)
VALUES 
("1", "C001", "500", "450", "465", "462", "465"),
("2", "C002", "700", "570", NULL, NULL, NULL),
("3", "C003", "600", "610", "605", "602", NULL),
("4", "C004", "300", NULL, NULL, NULL, NULL),
("5", "C005", "400", "425", NULL, NULL, NULL),
("6", "C006", "900", "870", "868", NULL, NULL),
("7", "C007", "350", "360", "372", "375", "390"),
("8", "C008", "250", "290", NULL, NULL, NULL);

In the table above I have different campaigns with their corresponding quantities .在上表中,我有不同的campaigns及其相应的quantities
The quantities are filled in different columns . quantities填写在不同的columns


Now, I want to get the latest available quantity for each campaign based on the following hierarchy:现在,我想根据以下层次结构获取每个campaign最新可用数量

quantity_completed > quantity_recorded > quantity_delivered > quantity_ordered > quantity_offered

The result should look like this:结果应如下所示:

Campaign      Quantity
C001            465
C002            570
C003            602
C004            300
C005            425
C006            870
C007            390
C008            290

What query do I need to achieve this?我需要什么查询来实现这一目标?

Use coalesce() :使用coalesce()

select campaign, coalesce(quantity_completed, quantity_recorded, quantity_delivered, quantity_ordered, quantity_offered) as quantity
from logistics;

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

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