0

这是我正在使用的查询:

select top 1 'Return To IPACS' as name, 'http://domain:88' as link 
union 
select name,link 
from jrm_intranetlinks l 
inner join jrm_intranetpermissions p on l.id = p.linkid 
where p.userid = 155
order by case name when 'Home' then 2 when 'Team' then 1 end desc, name

这是我收到的错误消息:

Msg 104, Level 16, State 1, Line 1
ORDER BY items must appear in the select list if the statement contains a UNION, INTERSECT or EXCEPT operator.

上面的底部集合返回我们用于链接名称的列表,右列提供它们链接到的路径。我们需要为每个人添加一个默认链接,这就是我们尝试联合部分的原因,因为这个链接每个人都会得到,而另一个表显示基于权限的链接。

如果没有 order by 子句,它工作得很好,但我需要返回到顶部的 ipacs 一个,然后是 home,然后是 team and rest ordered desc。

我在这里做错了什么?

4

6 回答 6

2

怎么样:

select 
    'Return To IPACS' as name, 
    'http://domain:88' as link, 
    1 as sort_me 
union all
(select 
    name, 
    link, 
    2 as sort_me 
from jrm_intranetlinks l 
inner join jrm_intranetpermissions p on l.id = p.linkid 
where p.userid = 155 )
order by sort_me

我担心你的筑巢。我加了一些括号。无论如何,关键是您应该只添加如图所示的值来强制排序。

于 2013-07-02T21:49:24.530 回答
2
select 
    'Return To IPACS' as name, 
    'www.home.com' as link,
    3 sortOrder
union all
select 
    name, 
    link,
    case name 
        when 'Home' then 2 
        when 'Team' then 1 
    end sortOrder
from links l
inner join jrm_intranetpermissions p on l.id = p.linkid 
where p.userid = 155 
order by sortOrder desc

演示

于 2013-07-02T22:06:18.030 回答
1

你所拥有的是两个不同的“列”......

l.[Name] 

(case [Name] when 'Home' then 2 when 'Team' then 1 end)

...前者在选择列表中,而后者不在。

存在几种解决方法。我最喜欢的是...

select top 1 'Return To IPACS' as [Name]
    ,'http://domain:88' as [Link]
    , 3 as [Order]

union 

select l.name as [Name]
    ,l.link as [Link]
    ,(case [Name] when 'Home' then 2 when 'Team' then 1 end) as [Order]
from jrm_intranetlinks l
inner join jrm_intranetpermissions p on l.id = p.linkid 
where p.userid = 155
order by [Order], [Name]
于 2013-07-02T22:14:06.510 回答
0

ORDER BY您只选择“名称”和“链接”,因此当您使用UNIONINTERSECT或时,这些是您可以使用的唯一项目EXPECT

换句话说,您需要将 ' order by' 子句中的所有项目添加到您的 select 语句中。

于 2013-07-02T21:49:57.870 回答
0
select name,link from (
  select
    'Return To IPACS' as name,
    'http://domain:88' as link,
    0 as sort_order
  union 
  select
    name,
    link
    case name when 'Home' then 1 when 'Team' then 2 as sort_order
  from jrm_intranetlinks l 
  inner join jrm_intranetpermissions p on l.id = p.linkid 
  where p.userid = 155
) t
order by sort_order, name
于 2013-07-02T22:03:37.993 回答
0

您是否尝试将其设为内部查询并在外部指定订单?

像这样的东西:

select name, link
from (
    select top 1 'Return To IPACS' as name, 'http://domain:88' as link 
    union 
    select name,link 
    from jrm_intranetlinks l 
    inner join jrm_intranetpermissions p on l.id = p.linkid 
    where p.userid = 155
) tbl
order by case name when 'Home' then 2 when 'Team' then 1 end desc, name
于 2013-07-02T21:53:20.803 回答