以非常特定的方式对一些查询结果进行排序

时间:2019-07-10 02:03:29

标签: sql select sql-order-by

我需要以以下特定方式对以下查询的结果进行排序:

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

最后两行的列具有相同的条件,因此顺序无关紧要。

1 个答案:

答案 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