sql server desired output from tables
1 2 3 4 5 6 7 8 | ID name Dept Manager 101 Mukesh SW 102 Ram SW 101 103 sham SW 101 104 rahul SW 101 105 Rajat HQ 106 akhilesh HQ 105 107 sachin HQ 105 |
我有这个表,我想输出如下
1 2 3 4 5 | dep Manager name SW Mukesh Ram Sham Rahul HQ Rajat akhilesh |
号
请根据您的需要查找下面的查询。我创建了mytest作为需要替换的表名。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | SELECT CASE WHEN ISNULL(SecondTable.Id,0) = 0 THEN FirstTable.Dept ELSE '' END AS Department, CASE WHEN ISNULL(SecondTable.Id,0) = 0 THEN Manager.Name ELSE '' END AS Manager, FirstTable.Name FROM MyTest AS FirstTable LEFT JOIN MyTest AS SecondTable ON SecondTable.ID = (SELECT Top 1 MyTest.ID FROM MyTest WHERE MyTest.Manager = FirstTable.Manager AND MyTest.dept = FirstTable.dept AND MyTest.Id < FirstTable.Id ORDER BY MyTest.ID DESC) LEFT JOIN MyTest AS Manager ON Manager.Id = FirstTable.Manager WHERE FirstTable.Manager <> 0 ORDER BY FirstTable.dept, FirstTable.ID |
这仅在SQL中是不可能的。你所能做的就是为他们中的每一个获得DEP和经理的名字。
1 2 3 | SELECT t1.Dept AS DEP, t2.name AS MANAGER, t1.name AS NAME FROM table1 t1 INNER JOIN table1 t2 ON t1.manager = t2.id |
SQLFiddle拆卸
这将返回如下内容:
1 2 3 4 5 6 | DEP MANAGER NAME SW Mukesh Ram SW Mukesh sham SW Mukesh rahul HQ Rajat akhilesh HQ Rajat sachin |
号
然后,在您选择的编程语言中,您将进行格式化。
您要查找的是检索层次结构数据,使用SQL 2008可以使用公共表表达式。使用公共表表达式检查此链接递归查询数据输出是平面的(它将为每行重复sw和mukesh)。希望有帮助