如何对包含连字符的凭证编号(如SI-18-08-1,CRV-18-09-1)进行排序

时间:2019-06-23 04:28:34

标签: tsql

我想按照对党的升序对凭证进行排序。

尚未尝试。

select * 
from 
  (select v.VoucherDate,
    case 
      when v.VoucherNo like 'SI%' then 'a' 
      else 'b' 
    end as [Type]
    ,v.Particular
    ,v.VoucherNo,isnull((at.Debit),0) as Debit
    ,isnull((at.Credit),0) as Credit 
  from Vouchers v
  left join 
  (select 
    at.VoucherId
    ,at.PartyId 
    ,isnull(SUM(at.DebitAmount),0) as Debit
    ,isnull(sum(at.CreditAmount),0) as Credit 
    from AccountsTransaction at 
    where at.PartyId=5106
    group by at.VoucherId,at.PartyId
    ) at  on at.VoucherId=v.VoucherId
  where at.PartyId=5106
  ) as Temptbale
order by Temptbale.VoucherDate

1 个答案:

答案 0 :(得分:1)

如果VoucherNo始终包含4个部分,并用破折号分隔(并且不包含任何点),我将使用PARSENAME对其进行拆分,然后按每个组件进行排序:

DECLARE @Vouchers TABLE (VoucherNo VARCHAR(30) PRIMARY KEY)
INSERT INTO @Vouchers (VoucherNo)
VALUES ('SI-18-08-1'),('CRV-18-09-1')

SELECT *
FROM @Vouchers
ORDER BY PARSENAME(REPLACE(VoucherNo,'-','.'),4), 
         PARSENAME(REPLACE(VoucherNo,'-','.'),3), 
         PARSENAME(REPLACE(VoucherNo,'-','.'),2), 
         PARSENAME(REPLACE(VoucherNo,'-','.'),1)