在sql server中按日期列降序报告顺序?

时间:2014-05-22 07:32:56

标签: sql sql-server stored-procedures

这是我的疑问:

SELECT
  DR.name as tradername,
  convert(varchar,DR.Receiveddate,103) as recdate,
  DR.Recamount,
  DR.Chequeno,
  DR.Remark,
  DR.Updatedby 
FROM K_HM_ChicksaleDueReport DR 
where 
  DR.Receiveddate between @fromdate and @todate 
  and DR.name=@name

union all

Select 
  CS.name as tradername,
  convert(varchar,CS.chicksplaceddate,103) as recdate,
  CS.Recamount,
  '' as chequeno,
  'Direct' as Remark,
  CS.Updatedby 
from K_HM_ChickSales CS
where 
  CS.Recamount>0 
  and  CS.chicksplaceddate between @fromdate and @todate 
  and CS.name=@name 

order by recdate desc

使用这个我只按天降序收到报告。但我想要的是总 dd / mm / yyyy 明智的降序。

类似的东西:

22/05/2014
21/05/2014
10/04/2014
 5/03/2014 

3 个答案:

答案 0 :(得分:2)

由于recdate是VARCHAR,因此按个别字符排序。

首先尝试将recdate转换/转换回DATE,如下所示:

ORDER BY CAST(recdate AS DATETIME) DESC

答案 1 :(得分:2)

您必须像我猜的那样更改您的查询

select tradername,
 convert(varchar,recdate,103) as recdate,Recamount,Chequeno,Remark,Updatedby from (
SELECT
  DR.name as tradername,
  DR.Receiveddate as recdate,
  DR.Recamount,
  DR.Chequeno,
  DR.Remark,
  DR.Updatedby 
FROM K_HM_ChicksaleDueReport DR 
where 
  DR.Receiveddate between @fromdate and @todate 
  and DR.name=@name

union all

Select 
  CS.name as tradername,
  CS.chicksplaceddate as recdate,
  CS.Recamount,
  '' as chequeno,
  'Direct' as Remark,
  CS.Updatedby 
from K_HM_ChickSales CS
where 
  CS.Recamount>0 
  and  CS.chicksplaceddate between @fromdate and @todate 
  and CS.name=@name 

) as o
order by recdate desc

答案 2 :(得分:1)

试试这个

select tradername,convert(varchar,recdate,103)as recdate,Recamount,chequeno,
remark,updatedby from (
SELECT  name as tradername,Receiveddate as recdate,Recamount,Chequeno,
Remark,Updatedby FROM K_HM_ChicksaleDueReport  
where Receiveddate between @fromdate and @todate 
and name like '%'+@name+'%'
union all
Select name as tradername,chicksplaceddate as recdate,Recamount,''as chequeno,'Direct' as Remark,Updatedby from K_HM_ChickSales 
where Recamount>0 and  chicksplaceddate between @fromdate and @todate and name like '%'+@name+'%')a   order by a.recdate  desc

end

else
select tradername,convert(varchar,recdate,103)as recdate,Recamount,chequeno,remark,updatedby from(
SELECT name as tradername,Receiveddate as recdate,Recamount, Chequeno,
Remark,Updatedby 
FROM K_HM_ChicksaleDueReport  where Receiveddate between @fromdate 
and @todate and name=@name
union all
Select name as tradername,chicksplaceddate as recdate,Recamount,''as chequeno,
'Direct' as Remark,Updatedby from K_HM_ChickSales 
where Recamount>0 and  chicksplaceddate between @fromdate and @todate 
and name=@name)a order by a.recdate  desc