Note that there are some explanatory texts on larger screens.

plurals
  1. POT-SQL convert rows to columns when trying to get bottom 5 values as columns?
    primarykey
    data
    text
    <p>I am using MS SQL Server 2005.</p> <p>I think PIVOT could help me here, but I can't figure it out. I must be over thinking. Here is the input</p> <pre><code>create table #myrows (id char(1), seq_i int, val char(10)) insert into #myrows values('A',1, 'A1') insert into #myrows values('A',2, 'A2') insert into #myrows values('A',3, 'A3') insert into #myrows values('A',4, 'A4') insert into #myrows values('A',5, 'A5') insert into #myrows values('A',6, 'A6') insert into #myrows values('A',7, 'A7') insert into #myrows values('A',8, 'A8') insert into #myrows values('A',9, 'A9') insert into #myrows values('A',10, 'A10') insert into #myrows values('B',1, 'B1') insert into #myrows values('B',2, 'B2') insert into #myrows values('B',3, 'B3') insert into #myrows values('B',4, 'B4') insert into #myrows values('B',5, 'B5') insert into #myrows values('B',6, 'B6') insert into #myrows values('C',1, 'C1') insert into #myrows values('C',2, 'C2') insert into #myrows values('C',3, 'C3') </code></pre> <p>I can do it with T-SQL when I passing the id. But I seems like there is an easy sql view that I could create that doesn't require me to send it the id. Here is the T-SQL that gets me the output I want for one id:</p> <pre><code>DECLARE @max_hierarchy int DECLARE @code CHAR(1) select @code = 'C' SELECT @max_hierarchy = max(seq_i) FROM #myrows WHERE id=@code SELECT top 1 (SELECT val from #myrows WHERE id=@code AND seq_i = @max_hierarchy) AS 'Level1', (SELECT val from #myrows WHERE id=@code AND seq_i = @max_hierarchy-1) AS 'Level2', (SELECT val from #myrows WHERE id=@code AND seq_i = @max_hierarchy-2) AS 'Level3', (SELECT val from #myrows WHERE id=@code AND seq_i = @max_hierarchy-3) AS 'Level4', (SELECT val from #myrows WHERE id=@code AND seq_i = @max_hierarchy-4) AS 'Level5' from #myrows WHERE id=@code </code></pre> <p>Ideally this would be be my output of SQL I am looking for:</p> <pre><code>Code Level1 Level2 Level3 Level4 Level5 ---- ----------- ----------- ----------- ----------- ----------- A A10 A9 A8 A7 A6 B B6 B5 B4 B3 B2 C C3 C2 C1 NULL NULL </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload