Home Forums SQL Server 2008 SQL Server 2008 - General Distinct Data but order by on Priority Column Which is not present in select result. RE: Distinct Data but order by on Priority Column Which is not present in select result.

  • This seems to be a representation of what you are looking for.

    create table #Client

    (

    ClientID int identity,

    Name char(2)

    )

    insert #Client

    select 'C1' union all

    select 'C2' union all

    select 'C3'

    create table #Orders

    (

    OrderID int identity,

    ClientID int,

    OrderName char(2)

    )

    insert #Orders

    select 1, 'O1' union all

    select 1, 'O2' union all

    select 2, 'O3' union all

    select 2, 'O4' union all

    select 3, 'O5' union all

    select 3, 'O6'

    create table #OrderInfo

    (

    OrderInfoID int identity,

    OrderID int,

    Priority int

    )

    insert #OrderInfo

    select 1, 7 union all

    select 1, 1 union all

    select 2, 9 union all

    select 2, 3 union all

    select 3, 4 union all

    select 5, 2 union all

    select 7, 5 union all

    select 7, 8 union all

    select 8, 0

    select c.Name

    from #OrderInfo oi

    join #Orders o on oi.OrderID = o.OrderID

    join #Client c on c.ClientID = o.ClientID

    group by c.Name

    order by max(oi.Priority)

    drop table #Client

    drop table #Orders

    drop table #OrderInfo

    Notice how I posted this in a consumable format?

    I would HIGHLY recommend you change your naming conventions. You should not use a datatype prefix on your columns. I am assuming that things like "autClientId" and "vchName" mean "AutoNumberClientID" and "VarcharName". Not only does that make it difficult to find your columns, it will cause you untold pain when you have to change a datatype. You will end up with either LOTS of code to rework or prefixes that don't match anymore. Just don't it at all. It may seem like a good idea at first but you will soon realize how horrible that really is.

    _______________________________________________________________

    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/