如果行不存在则为空

时间:2017-08-03 16:10:32

标签: sql

我有以下代码。在某些情况下,没有t1.LineNo = 2所以我希望Val2只是空或空白。但我无法让它工作

select
    MOTRAN_HAJobFile.JobNumber
    ,MOTRAN_HAExtraChg.Description,MOTRAN_HAExtraChg.Value

    ,***(select t1.Value from MOTRAN_HAExtraChg t1
where MOTRAN_HAExtraChg.JobUniqueKey = t1.JobUniqueKey
and t1.LineNo = 2)  as  Val2***

from
    MOTRAN_HAJobFile
    left outer join
    MOTRAN_HAExtraChg
    on MOTRAN_HAExtraChg.JobUniqueKey = MOTRAN_HAJobFile.UniqueKey
where
    MOTRAN_HAJobFile.JobNumber = '235416'

EDITED

Job              line        Description                     Value
235416             1          Sunday Collection               325
235416             2         Rush Charge                     82     

这是表,但我的代码就像这样

Job        Description               Value     Description2     Value 2
235416    Sunday Collection           325      Rush Charge     82  

第2行不会一直存在,这是我的问题我只想让它然后留下描述2和值2空白

1 个答案:

答案 0 :(得分:0)

样本表和数据

CREATE TABLE jobfile
(job VARCHAR(6),
 line INT,
 description VARCHAR(50),
 value INT
)

INSERT INTO jobfile
VALUES ('235416',1,'Sunday Collection',325);

INSERT INTO jobfile
VALUES ('235416',2,'Rush Charge',82);

INSERT INTO jobfile
VALUES ('100001',1,'Sunday Collection',900);

job     line    description         value
235416  1       Sunday Collection   325
235416  2       Rush Charge         82
100001  1       Sunday Collection   900

查询

SELECT DISTINCT jf.job,
       (SELECT description FROM jobfile WHERE job = jf.job AND line = 1) AS description,
       (SELECT value FROM jobfile WHERE job = jf.job AND line = 1) AS value,
       (SELECT description FROM jobfile WHERE job = jf.job AND line = 2) AS description2,
       (SELECT value FROM jobfile WHERE job = jf.job AND line = 2) AS value2
  FROM jobfile jf

示例结果

job     description         value       description2    value2
100001  Sunday Collection   900         NULL            NULL
235416  Sunday Collection   325         Rush Charge     82