[英]How can I run a vlookup function in SQL within the same table?
I'm fairly new to SQL and struggling to find a good way to run the following query. 我对SQL还是很陌生,并且努力寻找一种运行以下查询的好方法。
I have a table that looks something like this: 我有一张桌子,看起来像这样:
NAME JOB GRADE MANAGER NAME
X 7 O
Y 6 X
Z 5 X
A 4 Z
B 3 Z
C 2 Z
In this table, it shows that Y and Z report into X, and A, B and C report into Z. 在此表中,它显示Y和Z报告为X,A,B和C报告为Z。
I want to create a computed column showing the grade each person's most senior direct report or "n/a" if they don't manage anyone. 我想创建一个计算列,显示每个人的最高级直接报告的等级,如果他们没有管理任何人,则为“不适用”。 So that would look something like this: 这样看起来像这样:
NAME JOB GRADE MANAGER NAME GRADE OF MOST SENIOR REPORT
X 7 O 6
Y 6 X N/A
Z 5 X 4
A 4 Z N/A
B 3 Z N/A
C 2 Z N/A
How would I do this? 我该怎么做?
SELECT g.*,isnull(convert(nvarchar, (SELECT max(g2.GRADE)
FROM dbo.Grade g2 WHERE
g2.manager =g.NAME AND g2.NAME!=g.NAME )),'N/A') as most_graded
FROM dbo.Grade g
The max will find out the topmost graded 最高会找出评分最高的
Input 输入项
X 7 O
y 6 X
Z 5 X
A 6 Z
C 2 Z
Output 输出量
X 7 O 6
y 6 X N/A
Z 5 X 6
A 6 Z N/A
C 2 Z N/A
Something like this: 像这样:
select name, job_grade, manager_name,
(select max(job_grade) from grades g2
where g2.manager_name = g1.name) as grade_of_most_recent_senior
from grades g1
order by name;
The above is ANSI SQL and should work on any DBMS. 以上是ANSI SQL,适用于任何DBMS。
SQLFiddle example: http://sqlfiddle.com/#!15/e0806/1 SQLFiddle示例: http ://sqlfiddle.com/#!15/e0806/1
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.