SELECT查询未按所需顺序返回

时间:2013-10-29 18:40:21

标签: sql sql-server

我希望按序号按顺序返回SELECTed查询。这是目前正在返回的内容:

enter image description here

这是当前的查询:

SELECT 
    [Number] + ' - ' + SUBSTRING([Title], 1, 40) AS [StoryName]
    ,[PK_Story]
FROM Story STY
INNER JOIN Task TSK ON TSK.StoryId = STY.PK_Story
INNER JOIN DailyTaskHours DTH ON DTH.TaskId = TSK.PK_Task
WHERE ProductId = @productIdParam
    AND DTH.ActivityDate BETWEEN @startDateParam
        AND @endDateParam
GROUP BY [Number]
    ,[Number] + ' - ' + SUBSTRING([Title], 1, 40)
    ,[PK_Story]
HAVING SUM(DTH.[Hours]) > 0
ORDER BY [Number] ASC

我试图通过[Number]订购,这是CMIS - ##。正如您所看到的,ORDER BY尝试执行此操作,但生成的顺序不正确。较低值'CMIS-43'不在顶部。我该如何解决这个问题?

编辑:

这最终是我处理[Number]的可变长度的解决方案:

SELECT [Number] + ' - ' + SUBSTRING([Title], 1, 40) AS [StoryName]
        ,[PK_Story]
FROM Story STY
INNER JOIN Task TSK ON TSK.StoryId = STY.PK_Story
INNER JOIN DailyTaskHours DTH ON DTH.TaskId = TSK.PK_Task
WHERE ProductId = @productParam
      AND DTH.ActivityDate BETWEEN @startDateParam
            AND @endDateParam
GROUP BY [Number]
     ,[Number] + ' - ' + SUBSTRING([Title], 1, 40)
     ,[PK_Story]
HAVING SUM(DTH.[Hours]) > 0
ORDER BY CAST(SUBSTRING([Number], CHARINDEX('-',[Number]) + 1, LEN([Number])) AS INT)

4 个答案:

答案 0 :(得分:3)

问题是您的列表正在按字符串排序,并且您希望它按数字排序。

尝试这样的事情:

SELECT [Number] + ' - ' + SUBSTRING([Title], 1, 40) AS [StoryName]
    ,[PK_Story], CAST(SUBSTRING([Number], 5, 3) AS int) AS [CMNumber]
FROM Story STY
INNER JOIN Task TSK ON TSK.StoryId = STY.PK_Story
INNER JOIN DailyTaskHours DTH ON DTH.TaskId = TSK.PK_Task
WHERE ProductId = @productIdParam
    AND DTH.ActivityDate BETWEEN @startDateParam
        AND @endDateParam
GROUP BY [Number]
    ,[Number] + ' - ' + SUBSTRING([Title], 1, 40)
    ,[PK_Story]
HAVING SUM(DTH.[Hours]) > 0
ORDER BY CMNumber ASC

答案 1 :(得分:2)

ORDER BY CAST(SUBSTRING([Number], 6, LEN([number])-5) AS INT) 

答案 2 :(得分:1)

[Number]是一个字符串/ varchar,因此排序是字典(字母)而不是数字。

答案 3 :(得分:0)

问题的根源在于您尝试对文本进行数字排序。换句话说,当数字10大于数字9时,字符串'9'大于字符串'10'。

要解决此问题,您必须使用select和group by子句的另一个字段。该字段将使用字符串函数来获取数字字段的数字部分,然后将其转换为整数。我会把细节留给你。