这是我的表:
Ref Num Status Task Status Task N
-----------------------------------------
TB011 RET Null 0
TB012 RET Null 0
TB013 INP Ready 100
TB013 INP Null 0
TB013 INP Null 0
TB014 INP In Process 100
TB014 INP Null 0
TB014 INP Null 0
TB015 INP Completed 100
TB015 INP Ready 200
TB015 INP Null 0
TB016 INP Ready 100
TB016 INP In Process 150
TB016 INP Null 0
TB017 INP Completed 100
TB017 INP In Process 150
TB017 INP Ready 199
TB017 INP Null 0
我需要获得每个“Ref Num”的唯一行,其中:
if Status = RET
只有一行,其中任务状态始终为空if Status = INP
我只需要任务状态未完成的第一行我添加“任务N”行是一个数字,也许它会有帮助
结果应该是这样的:
Ref Num Status Task Status Task N
------------------------------------------
TB011 RET Null 0
TB012 RET Null 0
TB013 INP Ready 100
TB014 INP In Process 100
TB015 INP Ready 200
TB016 INP Ready 100
TB017 INP In Process 150
!在参考编号,状态,任务状态,任务N之后,我有更多列,具有不同的数据,我也需要它们。
答案 0 :(得分:0)
我不知道数据库引擎。 但它可能看起来像这样:
SELECT * (
SELECT `Ref Num`,Status,`Task Status`,`Task N`
FROM table
WHERE Status = 'RET'
UNION
SELECT `Ref Num`,Status,`Task Status`,`Task N`
FROM table
WHERE Status = 'INP' AND
`Task Status` <> 'Completed'
GROUP BY `Ref Num`,Status
ORDER BY ORDER BY `Ref Num` ASC
) ORDER BY `Ref Num` ASC
答案 1 :(得分:0)
了解dbms对于解决方案选择至关重要,请在您的问题中指定dbms。此解决方案将匹配支持row_number()
的dbms的预期结果SELECT
Ref_Num
, Status
, Task_Status
, Task_N
FROM (
SELECT
Ref_Num
, Status
, Task_Status
, Task_N
, ROW_NUMBER() OVER (PARTITION BY REF_NUM
ORDER BY task_N ASC) AS RN
FROM table1
WHERE status = 'RET'
OR (status = 'INP'
AND task_status <> 'Completed'
AND task_n <> 0)
) d
WHERE rn = 1
ORDER BY
Ref_Num
;