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 ) dselect @bin = 1while @bin <= @max_bin_nobegin select @bins = isnull(@bins + ',', '') + quotename(convert(varchar(10), @bin)) select @bin = @bin + 1endselect @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 pivot ( max(bin_label) for bin_no in (' + @bins + ') ) p'print @sqlexec (@sql)
KH[spoiler]Time is always against us[/spoiler]