[英]How to order by column minus first character in a select distinct statement
我需要在select distinct语句中按顺序组织基于列的查询。 select distinct语句将字符连接到数字的前面(即“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
ps.Param_Value
ORDER BY ps.Param_Value
因为我的select distinct语句中没有ps.Param_Value
。 bookID
订购,因为由于前面的字母而导致结果未正确排序。 SUBSTRING(bookID, 1, 10)
排序,但除非我在我的select语句中放置SUBSTRING(bookID, 1, 10)
,否则它将无法工作由于它是一个select distinct语句。 那么有没有一种方法可以通过连接'S'后面的数字来排序,而不会在我的select语句中添加额外的内容。 或者是否可以将ps.Param_Value
添加到我的select distinct语句中,而不会实际返回到我的数据中?
对于您的特定示例,您可以使用
order by DataLine
ps.Param_Value
值是字符串的第一个非常量元素,所以这应该做你想要的。
更通用的解决方案是使用group by
然后使用order by min(ps.Param_Value)
。
我不确定我100%跟随,但我相信你可以:
(您可能希望明确列出所有列,但为了简洁,我省略了它们)
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
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.