我们说Employee和Shippers表有以下数据。
EmployeeID Name
1 Davolio
2 Fuller
3 Leverling
4 Peacock
5 Buchanan
6 Suyama
7 King
8 Callahan
9 Dodsworth
10 West
ShipperID ShipperName
1 Speedy Express
2 United Package
3 Federal Shipping
以下查询按降序返回ShipperID。
select ShipperID from Shippers order by ShipperID desc;
现在,我想以与检索ShipperID相同的顺序(3,2,1
)从Employee表中检索名称。我的预期输出为Leverling, Fuller, Davolio
。
select Name from Employee where EmployeeID in (select ShipperID from Shippers order by ShipperID desc)
上述查询未按预期返回数据。如何解决这个问题?
更新:
这不是按升序或降序排列记录。这只是我在这里发布的一个例子。为了更清楚,假设子查询将ShipperID作为2,3,1
返回。现在我想从Employee表中检索记录,如Fuller, Leverling, Davolio
答案 0 :(得分:3)
如果要保留订购,则必须加入这两个表。如果使用IN
答案 1 :(得分:1)
试试这个
select distinct Employee.Name from Employee
inner join Shippers on Shippers.ShipperID=Employee.EmployeeID
order by Shippers.ShipperID desc
答案 2 :(得分:0)
你试过吗
select Name from Employee where EmployeeID in (select ShipperID from Shippers ) order by ShipperID desc
答案 3 :(得分:0)
select Name from Employee where EmployeeID in (select ShipperID from Shippers ) order by EmployeeID desc
作为employeeid = shipperid,您可以通过employeeid订购
答案 4 :(得分:0)
如果您希望结果以特定顺序显示,那么您将不得不选择要按顺序排列的内容。在您的示例中,这意味着添加一列来定义发货人的订单,然后将其加入到员工表中,以便您可以相应地订购员工结果。
类似的东西:
WITH employees AS (SELECT 1 employeeid, 'Davolio' NAME FROM dual UNION ALL
SELECT 2 employeeid, 'Fuller' NAME FROM dual UNION ALL
SELECT 3 employeeid, 'Leverling' NAME FROM dual UNION ALL
SELECT 4 employeeid, 'Peacock' NAME FROM dual UNION ALL
SELECT 5 employeeid, 'Buchanan' NAME FROM dual),
shippers AS (SELECT 1 shipperid, 'Speedy Express' shippername FROM dual UNION ALL
SELECT 2 shipperid, 'United Package' shippername FROM dual UNION ALL
SELECT 3 shipperid, 'Federal Shipping' shippername FROM dual)
-- end of mimicking your tables, see SQL below:
SELECT emp.employeeid,
emp.name
FROM employees emp
INNER JOIN (SELECT shipperid,
CASE WHEN shipperid = 1 THEN 3
WHEN shipperid = 2 THEN 1
WHEN shipperid = 3 THEN 2
END order_id
FROM shippers) shp ON emp.employeeid = shp.shipperid
ORDER BY shp.order_id ASC;
EMPLOYEEID NAME
---------- ---------
2 Fuller
3 Leverling
1 Davolio
您的order_id列可能已经存在(例如时间戳列)或生成(通过上面演示的显式案例陈述,或使用row_number()
分析函数)但是如果您想要结果要按特定顺序出现,您需要该列。