简体   繁体   中英

How to Join single table to it self in SQL Server 2008?

I am using below table structure, I want to create a view which will show a FirstName of ReportsTo field shown below.

表结构

Please let me give a suggestion how to create that view which will display all the reports to 's first name with (',') comma separator.

From what I gather, I think you're trying to get the Firstname column and the ReportsTo column separated by a comma:

SELECT FirstName + ', ' + ReportsTo
FROM table

Edit: judging from the comments he's trying to do something else? Can someone rephrase for me?

SELECT  E.*,
        R.FirstName
FROM    Employees E
        JOIN Employees R
            ON E.ReportsTo LIKE '%' + R.EmpCode + '%'

You join a table to itself just like any other join. The main this is to make sure both tables are aliased with differnt aliases

Your problem is that you have a one to many relationship stored in the table which is a huge design mistake. For the future, remember that anytime you think about storing information a comma delimted list, then you are doing it wrong and need a related table instead. So first you have to split the data out into the related table you should have had instead with two columns, EmplCode and ReportsTo (with only one value in reports to), then you can do the join just like any other join. We use a function that you can get by searching around the internet called fn_split to split out such tables when we get this type of infomation in client files.

If you search out fn_split, then this is how you can apply it:

Create table  #UnsplitData (EmpCode varchar (10), ReportsTo varchar(20), FirstName varchar (10)) 
insert into #UnsplitData
values ('emp_0101', 'emp_0102,emp_0103', 'John')
, ('emp_0102', 'emp_0103', 'Sally')
, ('emp_0103', Null, 'Steve')



select *, employee.FirstName + ', ' + Reports.FirstName
from  #UnsplitData Employee 
join 
(
    select t.EmpCode , split.value  as Reportsto, ReportName.Firstname
    from  #UnsplitData t
    cross apply dbo.fn_Split( ReportsTo, ',') split
    join #UnsplitData ReportName 
        on ReportName.EmpCode = split.value
) Reports
    On Employee.EmpCode = Reports.empcode

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM