日期:2014-05-17  浏览次数:20483 次

SQL不能排序的问题。
select distinct  aa.CustomType,aa.LoanBlankDate,
(select BrachName from CAPS_BrachIns where ID =CAST(substring(aa.ContractNm ,2,2) as Int)) wd,
aa.CustomName,aa.ContractNm,aa.PeriodInterst,
isnull(c.receivableAmount,0),isnull(aa.PeriodInterst,0)-isnull(c.receivableAmount,0) receivebalance


 from
(select b.CustomType,a.LoanBlankDate,a.CustomName,a.ContractNm,a.PeriodInterst,a.PeriodNm,a.IsAdvanceBlack
from InterestList a
 
 left join OPSInf b on
 a.ContractNm=b.LoanNm  
where convert(varchar(10),LoanBlankDate,120) between  '2013-08-26' and '2013-09-19'


 
) aa 
   
  left join
  
  InterestReceive c on c.ContractNm=aa.ContractNm and  c.PeriodNm=aa.PeriodNm  and c.RepayType='PeriodInterst' 
   where aa.IsAdvanceBlack!='true' order by aa.CustomType,aa.LoanBlankDate,wd


一直很奇怪,这个代码最后一句排序,不能按照WD字段进行,其他2个字段可以排序

------解决方案--------------------
语法没问题。应该也不会报错。应该是楼主的逻辑有问题。说一下你的SQL的执行顺序吧:
#1.from aa left join InterestReceive
#2.WHERE   aa.IsAdvanceBlack != 'true'
#3.select后面所有字段及其计算值
#4.DISTINCT
#5.ORDER BY
------解决方案--------------------
引用:
当然不能按照WD字段排序,你要搞明白
order by aa.CustomType,aa.LoanBlankDate,wd是什么意思。
只有在aa.CustomType,aa.LoanBlankDate这两个字段的数据一样的情况下才会考虑按照WD来排序。

这样的写法排序时先考虑aa.CustomType,相同的时候在考虑aa.LoanBlankDate,然后再考虑WD


分析到位