我无法解决问题。任务是:
显示有老板号码和姓名的员工姓名和人数。
如下所示:
只有一张桌子:
到目前为止我试过这个:
SELECT
ID,
Name,
Boss,
(SELECT Name FROM Employees WHERE ID IN (SELECT Boss FROM Employees))
FROM Employees
但它给了我一个错误:
"子查询返回的值超过1。当子查询跟随=,!=,<,< =,>,> =或子查询被用作子查询时,不允许这样做 表达式"
我很感谢你的帮助。
答案 0 :(得分:8)
你需要一个自我加入;类似的东西:
Select a.ID, a.Name, b.ID, b.Name
from Employees A
left join Employees B
on a.Boss = b.ID
答案 1 :(得分:2)
执行此操作的一种方法是限制子查询仅使用Sub SpiltData()
Dim rngRead As Range
Dim rngReadRow As Range
Dim rngReadCell As Range
Dim arrSplit As Variant
Dim intWriteRow As Integer
'initialize intWriteRow
intWriteRow = 1
'get that range
Set rngReadRow = Sheets("Data").Range("J6").CurrentRegion
'loop through each row
For Each rngReadRow In rngReadRow.Rows
'split your carriage return delimited cell into an array
arrSplit = Split(rngReadRow.Cells(1, 11), Chr(10))
'iterate the array and write out
For Each arrItem In arrSplit
'by iterating each cell in the readrow
For Each rngReadCell In rngReadRow.Cells
'and writing it to the other worksheet
Sheets("Hours Sorted").Cells(intWriteRow, rngReadCell.Column).Value = rngReadCell
'increment the row to which we are writing
intWriteRow = intWriteRow + 1
Next rngReadCell
'and now write the split out value in the array
Sheets("Hours Sorted").Cells(intWriteRow, 11) = arrItem
Next arrItem
Next rngReadRow
End Sub
子句返回第一个结果。您还需要将它连接到主表:
TOP
答案 2 :(得分:2)
实际上,我必须在Azure数据库中创建一个类似的拆分。使用标题分隔性别(男人和女人)。
这是代码的一部分。
select
(Select count(b.TITLE) from SalesLT.Customer b Where Title LIKE 'Mr%') as women
,(Select count(c.TITLE) from SalesLT.Customer c Where Title LIKE 'Ms%') as men
,(Select count(d.TITLE) from SalesLT.Customer d Where Title NOT LIKE 'Ms%' AND Title NOT LIKE 'Mr%' ) as unidentified
,count(a.TITLE) as Total
from SalesLT.Customer a
有用吗?
答案 3 :(得分:1)
APH的答案肯定是最有效的解决方案。但是,我想添加一个带有相关子查询的解决方案,以表明您已经非常接近工作查询。
SELECT
E.ID,
E.Name,
E.Boss,
(SELECT Name FROM Employees WHERE ID = E.Boss) AS BossName
FROM Employees E
原始查询的问题在于子查询中的条件不依赖于特定记录。子查询返回了作为其他人老板的每个员工的姓名。
请注意,此解决方案通常具有比连接更差的性能,因为它必须为每个项执行子查询。虽然结果等同于连接的结果,但许多优化器没有意识到这一点,因为它们不接触子查询。