Please start any new threads on our new site at We've got lots of great SQL Server experts to answer whatever question you can come up with.

Our new SQL Server Forums are live! Come on over! We've restricted the ability to create new threads on these forums.

SQL Server Forums
Profile | Active Topics | Members | Search | Forum FAQ
Save Password
Forgot your Password?

 All Forums
 SQL Server 2008 Forums
 Transact-SQL (2008)
 Change result set layout
 Reply to Topic
 Printer Friendly
Author Previous Topic Topic Next Topic  

Starting Member

27 Posts

Posted - 05/13/2014 :  02:53:12  Show Profile  Reply with Quote
Hi Everyone,

I am interested in changing the way that data is displayed in my result set.

Essentially I want to display a selection of rows (1 to n) as columns, the following diagram explains my intentions -

Perhaps one of the greatest challenges here is the fact that I do not have a concrete number of rows (or BIN numbers).

Each stock item could be stored in one or more BINS, which I will not know until running my query.

Any suggestions here will be greatly appreciated.

Kind Regards,


In (Som, Ni, Yak)

17689 Posts

Posted - 05/13/2014 :  05:44:46  Show Profile  Reply with Quote

declare @max_bin_no int,
        @bin        int,
        @bins       varchar(max),
        @sql        varchar(max)

select  @max_bin_no = max(cnt)
from    (
            select  so_due_date, whs_code, qty_on_hand, cnt = count(*)
            from    table
            group by so_due_date, whs_code, qty_on_hand
        ) d

select  @bin = 1
while   @bin <= @max_bin_no
        select @bins = isnull(@bins + ',', '') + quotename(convert(varchar(10), @bin))
        select @bin  = @bin + 1

select  @sql = 
    select *
    from   (
                select so_due_date, whs_code, qty_on_hand, bin_label,
                       bin_no = row_number() over ( partition by so_due_date, whs_code, qty_on_hand order by bin_label)
                from   table
           ) d
                for  bin_no in (' + @bins + ')
           ) p
print @sql
exec (@sql)

Time is always against us

Go to Top of Page

Starting Member

27 Posts

Posted - 05/14/2014 :  02:02:11  Show Profile  Reply with Quote
Thank you KH
Go to Top of Page
  Previous Topic Topic Next Topic  
 Reply to Topic
 Printer Friendly
Jump To:
SQL Server Forums © 2000-2009 SQLTeam Publishing, LLC Go To Top Of Page
This page was generated in 0.03 seconds. Powered By: Snitz Forums 2000