ORDER BY与特定关键字的相关数据

时间:2018-06-08 04:41:03

标签: sql sql-server tsql stored-procedures

SELECT 
    Users.user_id, Users.location, Profession.name
FROM 
    Users
FULL OUTER JOIN 
    User_Education ON Users.user_id = User_Education.user_id
INNER JOIN 
    Profession ON Profession.profession_id = Users.desired_job
FULL OUTER JOIN 
    Exp_Duration ON Exp_Duration.user_id = Users.user_id
FULL OUTER JOIN 
    User_Skill ON Users.user_id = User_Skill.user_id
WHERE 
    1 = 1 
    AND Users.user_id IN (1491, 1493, 1497, 1498)           
    AND Users.active = 1 

我正在尝试对从此查询返回的结果进行排序以匹配关键字。例如,我希望能够传入“软件工程师”,并查看在“职业”表中具有活动记录的用户才能显示在顶部。实现这一目标的最有效方法是什么?

这是我使用过的许多不成功的方法之一:

SELECT 
    Users.user_id, Users.location, Profession.name
FROM 
    Users
FULL OUTER JOIN 
    User_Education ON Users.user_id = User_Education.user_id
INNER JOIN 
    Profession ON Profession.profession_id = Users.desired_job
FULL OUTER JOIN 
    Exp_Duration ON Exp_Duration.user_id = Users.user_id
FULL OUTER JOIN 
    User_Skill ON Users.user_id = User_Skill.user_id
WHERE 
    1 = 1 
    AND Users.user_id IN (1491, 1493, 1497, 1498, 1503)           
    AND Users.active = 1 
ORDER BY 
    CASE
       WHEN Profession.name LIKE 'Software Engineer' 
          THEN 0 
          ELSE 1
    END, Profession.name ASC

4 个答案:

答案 0 :(得分:0)

请替换

Profession.name LIKE 'Software Engineer' 

使用

Profession.name LIKE ('%' + 'Software Engineer' + '%')

并测试它。

答案 1 :(得分:0)

混合full joininner join看起来并不合适。事实上,我几乎从不使用full join。实际上,查询中的大多数表都没有在查询中使用。

您似乎想要保留所有用户,因此我怀疑这是您想要的查询:

SELECT u.user_id, u.location, p.name
FROM Users u LEFT JOIN
     Profession p
     ON p.profession_id = u.desired_job
WHERE u.user_id IN (1491, 1493, 1497, 1498) AND         
      u.active = 1 
ORDER BY (CASE WHEN p.name LIKE '%Software Engineer%' THEN 1 ELSE 2 END),
         u.user_id;

如果您确实需要其他表(例如,从此查询中删除了列引用),请使用LEFT JOIN

答案 2 :(得分:0)

请试试这个:

DECLARE @keyword NVARCHAR(256) = N'Software Engineer'; 
***
ORDER BY  
     IIF([Profession].[name] LIKE '%' + @keyword + '%', NULL, '') ASC
    ,[Profession].[name] ASC;

答案 3 :(得分:0)

如果您没有使用任何外卡,则无法like

你还有其他事情发生,因为这对我来说很好。

declare @t table (p varchar(40));
insert @t values 
('cook'),
('cook'),
('cook'),
('engineer'),
('engineer'),
('engineer'),
('engineer'),
('cook'),
('mechanic'),
('mechanic');
select * 
from @t 
order by case when p = 'engineer' 
                   then 0
                   else 1
         end, 
         p;

engineer
engineer
engineer
engineer
cook
cook
cook
cook
mechanic
mechanic