Sagar Sagar - 8 days ago 7
SQL Question

how to sort query result in sql

Below is my query and i want to sort this query by description i.e with field ld.descrip. where to use order by in below query to sort data according to description.

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

Answer

Order by at the end of the united query alias in firts query only , (same number of corresponing type column)

  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: */
Comments