为什么我的存储过程不适用于所有记录?

时间:2016-01-21 12:31:52

标签: sql sql-server tsql stored-procedures

我有一个程序可以正确地返回由JobStatus正确排序 desc 的记录,即

3 = Current
2= Previous
1= Initial

即。状态3的记录位于顶部,状态2在3之后,然后是1.它可以工作,但我想放置另一个ORDERING过滤器,但无法弄清楚。问题是状态为2的记录应根据FROM-TO Dates排序。

SP:

   SELECT serviceinfo.pk_serviceinfo_serviceinfoid, 
       serviceinfo.fk_districts_serviceinfo_initialdistrictid, 
       serviceinfo.fk_personalinfo_serviceinfo_pid, 
       serviceinfo.fk_webusers_serviceinfo_userid, 
       serviceinfo.serviceinfoentrydatetime, 
       CONVERT(VARCHAR, serviceinfo.serviceinfofromdate, 106) AS 
       ServiceInfoFromDate, 
       serviceinfodepartment, 
       CASE serviceinfo.serviceinfotodate 
         WHEN '1900-01-01' THEN '' 
         ELSE CONVERT(VARCHAR, serviceinfo.serviceinfotodate, 106) 
       END                                                    ServiceInfoToDate, 
       serviceinfo.serviceinfoinitialbps, 
       serviceinfo.serviceinfoinitialdesignation, 
       serviceinfo.serviceinfoinitialbps, 
       personalinfo.personalinfoname, 
       districts.districtname, 
       serviceinfo.serviceinfojobstatus, 
       serviceinfo.serviceinfooffice, 
       serviceinfo.serviceinfocadre, 
       jobstatuses.statusname, 
       CASE serviceinfo.serviceinfoservicetype 
         WHEN 1 THEN 'Permanent' 
         WHEN 2 THEN 'Fixed Pay' 
         WHEN 3 THEN 'Contract' 
       END                                                    AS 
       ServiceInfoServiceType 
FROM   serviceinfo 
       LEFT JOIN districts 
              ON districts.pk_districts_districtid = 
                 serviceinfo.fk_districts_serviceinfo_initialdistrictid 
       INNER JOIN personalinfo 
               ON personalinfo.pk_personalinfo_id = 
                  serviceinfo.fk_personalinfo_serviceinfo_pid 
       LEFT JOIN jobstatuses 
              ON jobstatuses.pk_jobstatuses_jobstatusid = 
                 serviceinfo.serviceinfojobstatus 
       INNER JOIN web_users 
               ON web_users.userid = serviceinfo.fk_webusers_serviceinfo_userid 
WHERE  serviceinfo.fk_personalinfo_serviceinfo_pid = @pk_PersonalInfo_ID 
ORDER  BY serviceinfo.serviceinfojobstatus DESC 

应根据ServiceInfoFromDateServiceInfoToDate

进行排列
29 Dec 2015     15 Jan 2016  Current
14 Jan 2016     06 Feb 2016  Previous
06 Feb 2016     09 Apr 2016  Previous
08 Jan 2016     13 Jan 2016  Initial

状态为“上一页”的reocrds未根据日期排列

2 个答案:

答案 0 :(得分:1)

您可以在案例陈述中按字段添加其他查询顺序:

ORDER  BY serviceinfo.serviceinfojobstatus DESC, 
case when serviceinfo.serviceinfojobstatus= 2 then ServiceInfoFromDate end 

答案 1 :(得分:0)

你没有提到你遇到的确切问题,但你应该试试这个:

ORDER  BY serviceinfo.serviceinfojobstatus DESC 
,         serviceinfo.serviceinfofromdate
,         serviceinfo.serviceinfotodate

这将对源属性进行排序,而不是像查询中那样转换为varchar。我认为这是最好的。