1

我想让 SELECTed 查询按数字顺序返回。这是当前正在返回的内容:

在此处输入图像描述

这是当前的查询:

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

4 回答 4

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
于 2013-10-29T18:47:53.957 回答
2
ORDER BY CAST(SUBSTRING([Number], 6, LEN([number])-5) AS INT) 
于 2013-10-29T18:53:21.100 回答
1

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

于 2013-10-29T18:46:22.113 回答
0

您的问题的根源是您正在尝试对文本进行数字排序。换句话说,虽然数字 10 大于数字 9,但字符串“9”大于字符串“10”。

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

于 2013-10-29T18:48:20.867 回答