sql server希望从表中输出

时间:2013-10-25 08:32:58

标签: sql sql-server-2008

                                         
        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       

我有这张桌子,我想要输出如下

                                  
        dep    Manager    name          
        SW     Mukesh     Ram       
                          Sham          
                          Rahul         
        HQ     Rajat      akhilesh          


                                    

3 个答案:

答案 0 :(得分:1)

请根据需要查找以下查询。我创建了MyTest作为您需要替换的表名。

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

答案 1 :(得分:0)

您正在寻找的是检索分层数据,使用sql 2008可以使用公用表表达式。查看此链接Recursive Queries Using Common Table Expressions数据输出是平的(它将为每一行重复SW和Mukesh)。 希望它有所帮助

答案 2 :(得分:0)

这在sql中是不可能的。你能做的就是获得每个人的dep和manager名称。

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 demo

这将返回如下内容:

DEP MANAGER NAME
SW  Mukesh  Ram
SW  Mukesh  sham
SW  Mukesh  rahul
HQ  Rajat   akhilesh
HQ  Rajat   sachin

然后用您选择的编程语言进行格式化。