如何在sql中对查询结果进行排序

时间:2016-11-26 10:09:10

标签: mysql sql database

下面是我的查询,我想通过描述对该查询进行排序,即使用字段ld.descrip。在下面的查询中使用order by来根据描述对数据进行排序。

Select ld.fact_code as costFactorID,ld.fact_code + ' ' + ld.descrip +' ' +'(' + convert(varchar,cast(ld.factor as money),1)+ '/' + ld.unit + ')' as costFactor, ap.alpha_code, ap.code, ld.neighborhd,ap.code
                                        from lndfact ld 
                                        inner join app_lookup ap on ap.code like ld.neighborhd 
                                        inner join parcel p on p.neighborhd = ap.alpha_code 
                                        inner join assessments assmt on assmt.parcel_no = p.parcel_no 
                                        where  assmt.assesmt_no = @0 and ld.value_type = @1
                                        union All
                                        Select ld.fact_code as costFactorID,ld.fact_code + ' ' + ld.descrip +' ' +'(' + convert(varchar,cast(ld.factor as money),1)+ '/' + ld.unit + ')' as costFactor, ap.alpha_code, ap.code, ld.neighborhd,ap.code
                                        from lndfact ld 
                                        inner join app_lookup ap on ap.code like ld.neighborhd and ap.code = 77

1 个答案:

答案 0 :(得分:1)

仅在firts查询中的联合查询别名的末尾排序,(相应类型的列数相同)

  Select 
       ld.fact_code as costFactorID
      ,ld.fact_code + ' ' + ld.descrip +' ' +'(' + convert(varchar,cast(ld.factor as money),1)+ '/' + ld.unit + ')' as costFactor
      , ap.alpha_code
      , ap.code
      , ld.neighborhd
      ,ap.code
  from lndfact ld 
  inner join app_lookup ap on ap.code like ld.neighborhd 
  inner join parcel p on p.neighborhd = ap.alpha_code 
  inner join assessments assmt on assmt.parcel_no = p.parcel_no 
  where  assmt.assesmt_no = @0 and ld.value_type = @1
  union All
  Select 
       ld.fact_code 
      ,ld.fact_code + ' ' + ld.descrip +' ' +'(' + convert(varchar,cast(ld.factor as money),1)+ '/' + ld.unit + ')' 
      , ap.alpha_code
      , ap.code
      , ld.neighborhd
      ,ap.code
  from lndfact ld 
  inner join app_lookup ap on ap.code like ld.neighborhd and ap.code = 77
  ORDER BY alpha_code, code /* eg: */