SQLServer按IGNORE NULL值排序

时间:2017-08-16 03:44:49

标签: sql-server sql-server-2014

出于某种原因,我现在无法更改表格或更新数据。这里的问题是:

我在下面有menu_user表:

userID  menuID
(null)  2
(null)  3
1       3
2       1
3       2
4       5
5       0

userIDmenuID没有重复。问题是如何ORDER BY userID, menuID但是当userID具有NULL值时,它将查找具有相同menuID的另一行并将其放在此行之后。 menuID只有最大2个相同值,如果有,则另一个必须为NULL

预期订单结果:

userID  menuID
1       3
(null)  3
2       1
3       2
(null)  2
4       5
5       0

这里是脚本示例:

CREATE TABLE [dbo].[menu_user](
    [userID] [int] NULL,
    [menuID] [int] NULL
);

INSERT [dbo].[menu_user] ([userID], [menuID]) VALUES (NULL, 3);
INSERT [dbo].[menu_user] ([userID], [menuID]) VALUES (1, 3);
INSERT [dbo].[menu_user] ([userID], [menuID]) VALUES (2, 1);
INSERT [dbo].[menu_user] ([userID], [menuID]) VALUES (3, 2);
INSERT [dbo].[menu_user] ([userID], [menuID]) VALUES (4, 5);
INSERT [dbo].[menu_user] ([userID], [menuID]) VALUES (5, 0);
INSERT [dbo].[menu_user] ([userID], [menuID]) VALUES (NULL, 2);

ADDED 如果可能的话,我希望这个脚本为View(只选择SELECT with No Variable)。

4 个答案:

答案 0 :(得分:1)

这似乎可以解决问题。您需要做一些事情来将多行关联在一起。在这里,我选择使用left join

select
    m1.*
from
    menu_user m1
        left join
    menu_user m2
        on
            m1.userID is null and
            m1.menuID = m2.menuID and
            m2.userID is not null
order by
    COALESCE(m1.userID,m2.userID),m1.userID desc

结果:

userID      menuID
----------- -----------
1           3
NULL        3
2           1
3           2
NULL        2
4           5
5           0

希望你能看到它是如何实现其目标的。

答案 1 :(得分:0)

检查一下,排序有点乱,但这会给你想要的结果。

SELECT * FROM menu_user mu
ORDER BY mu.menuID,
CASE WHEN mu.userID IS NULL THEN mu.menuID END

答案 2 :(得分:0)

当menuID的非空用户超过1个时,使用左联接解决方案将产生重复项。这是另一种方法。

select userID, menuID
From (
select *, Case when a.UseriD is not null then cast(a.userID as float) else
            (select max(b.userID) + 0.1 from menu_user b where a.menuID = b.menuID and a.userID is null) end as SortCol
    from menu_user a
) c Order by  SortCol

答案 3 :(得分:-2)

尝试此查询:

SELECT * 
FROM menu_user mu
WHERE userID IS NOT NULL
ORDER BY mu.menuID