我有一个SQL表(tblRequests),其中包含不同用户提交的请求列表。字段是:
RequestID, UserID, DateSubmitted, Status
我有另一个表(tblImportantUsers),其中包含重要用户列表。该表只有一个UserID字段。
我想显示重要用户提交的请求。我可以使用以下查询来实现此目的:
select r.RequestID, r.UserID, r.DateSubmitted, r.Status
from tblRequests r left join tblImportantUsers u on r.UserID = u.UserID
order by u.UserID desc, r.DateSubmitted desc
但是,我只希望重要用户的主动请求显示在最顶层。应根据DateSubmitted字段对非活动请求进行排序。我甚至尝试过UNION方法,但它也不起作用。
如果我在请求表中没有添加任何额外的列,我有什么方法可以实现这一点吗?
由于
tblRequests中的数据:
RequestID UserID DateSubmitted Status
1 205 3/12/2016 0
2 208 3/16/2016 1
3 203 3/17/2016 0
4 241 3/17/2016 1
5 210 3/18/2016 0
6 205 3/18/2016 1
7 203 3/19/2016 1
8 241 3/19/2016 1
tblImportantUsers中的数据:
UserID
205
203
必填结果:
RequestID UserID DateSubmitted Status
7 203 3/19/2016 1
6 205 3/18/2016 1
8 241 3/19/2016 1
5 210 3/18/2016 0
4 241 3/17/2016 1
3 203 3/17/2016 0
2 208 3/16/2016 1
1 205 3/12/2016 0
答案 0 :(得分:1)
试试这个,它适用于redshift:
select
a.requestid
, a.userid
, a.datesubmitted
, a.status
from
tblrequests a
left join tblimportantusers b on (a.userid = b.userid)
order by
(case when status = 1 and b.userid is not null then 1 else 0 end) desc
, date submitted desc
, userid desc
答案 1 :(得分:0)
这应该这样做:
select RequestID, UserID, DateSubmitted, Status
from (
select r.RequestID, r.UserID, r.DateSubmitted, r.Status, 1 as ind
from tblRequests r inner join tblImportantUsers u on r.UserID = u.UserID
order by r.status desc, r.DateSubmitted desc
union all
select r.RequestID, r.UserID, r.DateSubmitted, r.Status, 0 as ind
from tblRequests r left outer join tblImportantUsers u on r.UserID = u.UserID
where u.UserID is null
order by r.status desc, r.DateSubmitted desc)
order by ind desc, DateSubmitted desc, userID
执行内连接和左外连接