0

union我想对语句的一侧进行排序,如下面的代码。但是不可能order byunion使用语句的一部分,当我使用view具有的部分时order by,这让我对整理中的冲突产生了一些错误。那么,我怎样才能仅通过union声明的一侧订购?

   select Creator
        , CreateDate
        , Subject 
     from tblWkfTicket 
   where tblWkfTicket.ID = @tikectID
union 
   select Creator
        , CreateDate
        , '' AS Subject
     from tblWkfPost 
    where TicketID = @tikectID
 order by tblWkfPost.ID
        ;
4

2 回答 2

2

您必须编写ORDER BY适用于整个结果集的应用程序。假设您实际上希望第一个查询的结果出现在第二个查询的结果之前,并且第二个查询的结果按 排序ID,您需要执行以下操作:

select Creator,CreateDate,Subject
from
  (
   select Creator
       , CreateDate
       , Subject,
       , 1 as resSet
       , 0 as ID 
   from tblWkfTicket 
   where tblWkfTicket.ID = @tikectID
  union all
   select Creator
       , CreateDate
       , '' AS Subject
       , 2
       , ID
   from tblWkfPost 
   where TicketID = @tikectID
  ) t
order by
 resSet,
 ID;
于 2013-07-09T07:57:43.557 回答
1

尝试

   select *
     from (
                   select 1    seq
                        , null postid
                        , emb.Creator
                        , emb.CreateDate
                        , emb.Subject
                     from (         
                               select Creator
                                    , CreateDate
                                    , Subject 
                                 from tblWkfTicket 
                                where tblWkfTicket.ID = @tikectID
                          ) emb
               union all
                   select 2    seq
                        , tblWkfPost.IDpostid
                        , Creator
                        , CreateDate
                        , '' AS Subject
                    from tblWkfPost 
                   where TicketID = @tikectID
          )
order by seq
       , postid
;

保证您的订购要求

于 2013-07-09T08:02:25.120 回答