gpt4 book ai didi

sql-server - 如何在sql server中使用 "like"搜索数据

转载 作者:行者123 更新时间:2023-12-04 00:07:28 26 4
gpt4 key购买 nike

我输入了一个词“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”的记录

最佳答案

在 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

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

关于sql-server - 如何在sql server中使用 "like"搜索数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16567722/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com