如何在选择非重复语句中按列减去第一个字符排序



我需要在选择非重复语句中按顺序根据列组织查询。选择非重复语句将字符连接到数字的前面(即"S1","S2"..."S11"(。

这是代码:

select distinct 
s.book_Id as EpbookId
,concat('S',ps.Param_Value) as bookID
,concat(sa.Location,'-',s.book_Number) as Label
,concat('<book ID="',concat('S',ps.Param_Value),
'" label="',concat(sa.Location,'-',s.book_Number),'"/>') as DataLine
from 
books s
inner join books_Address sa on 
s.book_Id = sa.book_Id 
and sa.Addr_Type_Id = 1
and s.bookS_TYPE_ID = 1
and s.Active = 1
inner join Parameters_books ps on 
ps.book_Id = s.book_Id
and ps.Param_Id = @bookParam
  1. 基本上我只需要按ps.Param_Value订购
  2. 问题是我不能使用简单的ORDER BY ps.Param_Value因为我的选择不同语句中没有ps.Param_Value
  3. 我也不能按bookID订购,因为结果没有排序 由于前面的字母正确。
  4. 我也尝试按SUBSTRING(bookID, 1, 10)排序,但同样,除非我在我的选择语句中SUBSTRING(bookID, 1, 10),否则它将无法工作,因为它是一个选择不同的语句。

那么有没有办法按连接"S"后面的数字排序,而无需在我的选择语句中添加额外的内容。或者是否可以将ps.Param_Value添加到我的选择不同语句中,而不会实际返回我的数据?

我不确定我是否 100% 遵循,但我相信你可以:

  • 保持ps.param_value与众不同
  • 在计算 S + 连接逻辑的不同块周围添加一个选择
  • 外部选择中按ps.param_value下订单

(您可能想明确列出所有列,但为了简洁起见,我在这里省略了它们(

SELECT 
*, 
concat('S',ps.Param_Value) as bookID
FROM
(
select distinct 
s.book_Id as EpbookId
,ps.Param_Value as Param_Value
,concat(sa.Location,'-',s.book_Number) as Label
,concat('<book ID="',concat('S',ps.Param_Value),
'" label="',concat(sa.Location,'-',s.book_Number),'"/>') as DataLine
from 
books s
inner join books_Address sa on 
s.book_Id = sa.book_Id 
and sa.Addr_Type_Id = 1
and s.bookS_TYPE_ID = 1
and s.Active = 1
inner join Parameters_books ps on 
ps.book_Id = s.book_Id
and ps.Param_Id = @bookPara
) A
ORDER BY
Param_Value

对于您的特定示例,您可以使用

order by DataLine

ps.Param_Value值是字符串的第一个非常量元素,因此这应该可以执行您想要的操作。

更通用的解决方案是使用group by然后使用order by min(ps.Param_Value).

select distinct 
EpbookId,CONCAT('S',bookID) AS bookId, Label, DataLine
from
(SELECT 
s.book_Id as EpbookId
,ps.Param_Value as bookID
,concat(sa.Location,'-',s.book_Number) as Label
,concat('<book ID="',concat('S',ps.Param_Value),
'" label="',concat(sa.Location,'-',s.book_Number),'"/>') as DataLine
from 
books s
inner join books_Address sa on 
s.book_Id = sa.book_Id 
and sa.Addr_Type_Id = 1
and s.bookS_TYPE_ID = 1
and s.Active = 1
inner join Parameters_books ps on 
ps.book_Id = s.book_Id
and ps.Param_Id = @bookParam
ORDER BY ps.param_value
) myTempView

相关内容

最新更新