我需要以以下特定方式对以下查询的结果进行排序:
1)在第一行中,IdItem
的值为IsComplete
= 0,并且同一IdItem
已经完成了一项任务(IsComplete = 1)
2)其余行按IdItem ASC
排序。
--Current Select
SELECT
IdTask,
IdTaskDetail,
IdTask,
IdItem,
IsComplete,
RealQty,
ProposalQty
from TaskDetail
where IdTask = 751
and IsComplete = 0
ORDER BY (ProposalQty - RealQty)/ProposalQty ASC, IdItem ASC
--Creating table and values inside
CREATE TABLE TaskDetail
(IdTaskDetail int,
IdTask int,
IdItem int,
IsComplete int,
RealQty int,
ProposalQty int)
--Values
insert into TaskDetail (IdTaskDetail, IdTask, IdItem, IsComplete, RealQty, ProposalQty)
values (1642, 751, 10820, 0, 0, 12)
insert into TaskDetail (IdTaskDetail, IdTask, IdItem, IsComplete, RealQty, ProposalQty)
values (1641, 751, 9228, 0, 0, 12)
insert into TaskDetail (IdTaskDetail, IdTask, IdItem, IsComplete, RealQty, ProposalQty)
values (1640, 751, 9228, 0, 0, 12)
insert into TaskDetail (IdTaskDetail, IdTask, IdItem, IsComplete, RealQty, ProposalQty)
values (1643, 751, 10820, 1, 12, 12)
--Current table data
IdTask IdTaskDetail IdTask IdItem IsComplete RealQty ProposalQty
751 1641 751 9228 0 0 12
751 1640 751 9228 0 0 12
751 1642 751 10820 0 0 12
751 1643 751 10820 1 12 12
期望的结果应该是这样(因为有一个IsComplete = 1任务带有项10820):
IdTask IdTaskDetail IdTask IdItem IsComplete RealQty ProposalQty
751 1642 751 10820 0 0 12
751 1640 751 9228 0 0 12
751 1641 751 9228 0 0 12
最后两行的列具有相同的条件,因此顺序无关紧要。
答案 0 :(得分:1)
您可以使用相关子查询来检查某行是否具有与IsComplete=1
相对应的行,并根据该顺序进行排序:
SELECT IdTask,
IdTaskDetail,
IdTask,
IdItem,
IsComplete,
RealQty,
ProposalQty
FROM TaskDetail t
WHERE IdTask = 751 AND IsComplete = 0
ORDER BY CASE WHEN EXISTS (SELECT *
FROM TaskDetail o
WHERE o.IdItem = t.IdItem AND
o.IdItem IsComplete = 1)
THEN 0
ELSE 1
END,
IdItem