通过在 SQL 服务器 select 中未给出预期结果来排序

Order by not giving expected results in SQL Server select

我有 select 语句 table 有两列,storebusinesskeybusinessdate

当我 运行 a select 并尝试按 storebusinesskey 对输出进行排序时,它不起作用。

SELECT
    t1.StoreBusinessKey, DateBusinessKey AS BusinessDate
FROM
    TABA t1
LEFT JOIN 
    TABB t2 ON t1.StoreBusinessKey = t2.StoreBusinessKey 
            AND t1.DateBusinessKey = t2.BusinessDate
WHERE
    t2.BusinessDate IS NULL
ORDER BY
    t1.StoreBusinessKey DESC

输出

StoreBusinessKey BusinessDate
C95 2022-03-15
C91 2022-03-27
C89 2022-03-09
C784 2022-03-22
C784 2022-03-15
C766 2022-03-22
C766 2022-03-29
C759 2022-03-22
C693 2022-03-22
C681 2022-03-22
C674 2022-03-30
C654 2022-03-30
C606 2022-03-30
C595 2022-03-29
C595 2022-03-30
C56 2022-03-30
C521 2022-03-30
C52 2022-03-30
C486 2022-03-27
C486 2022-03-30
C486 2022-03-26
C486 2022-03-29
C486 2022-03-28
C476 2022-03-29
C476 2022-03-30
C471 2022-03-30

如您所见,C52 应该排在首位,但事实并非如此。你能帮我先按 Storebusinesskey 排序,然后再按 businessdate 排序吗?

您对字符串值的排序。假设一个前导 alpha 和一些字符串操作,我们可以轻松地转换为 int 并排序

例子

Declare @YourTable Table ([StoreBusinessKey] varchar(50),[BusinessDate] varchar(50))
Insert Into @YourTable Values 
 ('C95','2022-03-15')
,('C91','2022-03-27')
,('C89','2022-03-09')
,('C784','2022-03-22')
,('C784','2022-03-15')
,('C52','2022-03-30')   -- Should be first
 
Select * 
 From  @YourTable
 Order By try_convert(int,substring([StoreBusinessKey],2,25))
         ,[BusinessDate]

结果

StoreBusinessKey    BusinessDate
C52                 2022-03-30
C89                 2022-03-09
C91                 2022-03-27
C95                 2022-03-15
C784                2022-03-15
C784                2022-03-22