如何在sql server 2008中使用不同的SUBSTRING

时间:2016-01-04 12:42:28

标签: sql sql-server sql-server-2008

我的查询是

select distinct PoNo, PoDate, SupplierId, BillNo
FROM Purchase_Product
order by  PoNo

如下所示 order

但我需要PO0001,Po0002,PO0003,PO0004 ......

所以,我正在使用

select distinct PoNo, PoDate, SupplierId, BillNo
FROM Purchase_Product
order by SUBSTRING(PoNo,5,1)

但是它显示了像

这样的错误
  如果SELECT DISTINCT为,则

ORDER BY项必须出现在选择列表中   指定。帮帮我

3 个答案:

答案 0 :(得分:4)

您可以改为使用GROUP BY

SELECT PoNo, PoDate, SupplierId, BillNo
FROM Purchase_Product
GROUP BY PoNo, PoDate, SupplierId, BillNo
ORDER BY SUBSTRING(PoNo, 5, 1)

答案 1 :(得分:0)

您也可以尝试以下一个:

SELECT PoNo, PoDate, SupplierId, BillNo
FROM (
    select distinct CAST(SUBSTRING(PoNo,2,LEN(PoNo)-2) AS INT) AS Pid, PoNo, PoDate, SupplierId, BillNo
    FROM Purchase_Product
) AS tbl
order by  Pid

答案 2 :(得分:0)

2.6

SELECT PoNo, PoDate, SupplierId, BillNo FROM Purchase_Product GROUP BY PoNo, PoDate, SupplierId, BillNo ORDER BY Cast(SUBSTRING(PoNo, 3, len(PoNo)) as int) 中提取数字并按该数字排序。