2

我输入了一个单词“boat”,所以我需要以boat 开头并且包含“boat”的记录。但必须首先出现以“boat”开头的记录

我试过以下

Select   AsiccCodeId,AsiccDescription             
FROM     AsiccCodeMaster  c             
WHERE    c.AsiccDescription like 'boat%' or c.AsiccDescription like '%boat%'

select a.* from
(

 Select   AsiccCodeId,AsiccDescription             
 FROM     AsiccCodeMaster  c             
 WHERE c.IsActive = 1  and (GoodFor = 'M' or GoodFor = 'B')
 and c.AsiccDescription like 'Unmilled%'



 UNION

 Select   AsiccCodeId,AsiccDescription             
 FROM     AsiccCodeMaster  c             
 WHERE c.IsActive = 1  and (GoodFor = 'M' or GoodFor = 'B')
 and c.AsiccDescription like '%Unmilled%'



 )a

但它给了我

4137    Combustion Boats 
6360    Boat, Fibre
6361    Boat, Rubber - Motorized
6362    Boat, Wooden Canal Boats
6363    Boat, Wooden With Engine
6370    Wooden Boats Body Building
6374    Boat, Rowing / Sports
6375    Boat, Rubber - Nonmotorized
6376    Boat, Wooden Without Engine-Others
6379    Parts Of Ships, Boats Etc., N.E.C
6391    Ships, Boats & Other Vessels, N.E.C
6394    Ships, Boats & Other Vessels, N.E.C

我需要首先以“boat”开头的记录,然后是包含“boat”的记录

4

2 回答 2

10

在 Order By 子句中使用 CASE 语句

SELECT   AsiccCodeId,AsiccDescription             
FROM     AsiccCodeMaster  c             
WHERE    c.AsiccDescription like '%boat%'
ORDER BY CASE WHEN c.AsiccDescription like 'boat%' THEN 0 ELSE 1 END, c.AsiccDescription

由于您希望首先出现以“boat”开头的标题,因此 CASE 语句将优先考虑这些标题。它查看每条记录,如果描述以“boat”开头,则为其分配排序值 0,否则为其分配排序值 1。 ORDER BY 默认按升序排序,因此会将所有 0 (以 'boat' 开头的那些)在所有 1 之前(其余记录)

于 2013-05-15T14:29:31.520 回答
3

你需要给你的结果一些排序!

SELECT a.* 
FROM
(
    SELECT 
       AsiccCodeId, AsiccDescription, Sequence = 1
    FROM AsiccCodeMaster  c             
    WHERE c.IsActive = 1 AND (GoodFor = 'M' or GoodFor = 'B')
      AND c.AsiccDescription LIKE 'Boat%'    

    UNION

    SELECT 
       AsiccCodeId, AsiccDescription, Sequence = 2
    FROM AsiccCodeMaster  c             
    WHERE c.IsActive = 1 AND (GoodFor = 'M' or GoodFor = 'B')
      AND c.AsiccDescription LIKE '%Boat%'    
) a
ORDER BY a.Sequence
于 2013-05-15T14:28:32.823 回答