Home Forums SQL Server 2005 T-SQL (SS2K5) T-SQL Function that works like the FIRST funcion in MS Access? RE: T-SQL Function that works like the FIRST funcion in MS Access?

  • I assumed some of the structures were not yours but the post that won't execute certainly was. At any rate I think that something like this will get you what you are looking for.

    with SortedData as

    (

    select e.*, s.SpaceType, s.Space_Number as Space_SpaceNumber, ROW_NUMBER() over (partition by s.Space_Number order by (select null)) as RowNum

    from employee e

    join spaces s on e.space_Number = s.space_id

    )

    select CC, Space_Number, SpaceType, Space_SpaceNumber,

    MAX(case when RowNum = 1 then FirstName end) as FirstName1,

    MAX(case when RowNum = 1 then LastName end) as LastName1,

    MAX(case when RowNum = 2 then FirstName end) as FirstName2,

    MAX(case when RowNum = 2 then LastName end) as LastName2

    from SortedData s

    group by

    CC, Space_Number, SpaceType, Space_SpaceNumber

    This is using a cte (common table expression). You should probably read up on them.

    Also, how if you care to explain, how can you just write s.Space_Number or e.First without using the whole "prefix" if you will. Like I said... I am terribly new to SQL.

    Chris is using an alias. I did the same thing in the code I just posted. You might want to read up on aliases in sql server. They will make your life a LOT easier.

    _______________________________________________________________

    Need help? Help us help you.

    Read the article at http://www.sqlservercentral.com/articles/Best+Practices/61537/ for best practices on asking questions.

    Need to split a string? Try Jeff Modens splitter http://www.sqlservercentral.com/articles/Tally+Table/72993/.

    Cross Tabs and Pivots, Part 1 – Converting Rows to Columns - http://www.sqlservercentral.com/articles/T-SQL/63681/
    Cross Tabs and Pivots, Part 2 - Dynamic Cross Tabs - http://www.sqlservercentral.com/articles/Crosstab/65048/
    Understanding and Using APPLY (Part 1) - http://www.sqlservercentral.com/articles/APPLY/69953/
    Understanding and Using APPLY (Part 2) - http://www.sqlservercentral.com/articles/APPLY/69954/