TEST 1

0

Please login or register to vote for this query.

(click on this box to dismiss)

Arduino Stack Exchange

Q&A for developers of open-source hardware and software that is compatible with Arduino

CREATE TABLE #yt 
(
  [Store] int, 
  [Week] int, 
  [xCount] int
);
    
INSERT INTO #yt
(
  [Store], 
  [Week], [xCount]
)
VALUES
    (102, 1, 96),
    (101, 1, 138),
    (105, 1, 37),
    (109, 1, 59),
    (101, 2, 282),
    (102, 2, 212),
    (105, 2, 78),
    (109, 2, 97),
    (105, 3, 60),
    (102, 3, 123),
    (101, 3, 220),
    (109, 3, 87);
    
SELECT * FROM #yt    
    
DECLARE @cols AS NVARCHAR(MAX),
    @query  AS NVARCHAR(MAX)

select @cols = STUFF((SELECT ',' + QUOTENAME(Week) 
                    from #yt
                    group by Week
                    order by Week
            FOR XML PATH(''), TYPE
            ).value('.', 'NVARCHAR(MAX)') 
        ,1,1,'')

SELECT * FROM #yt    

/*
set @query = 'SELECT store,' + @cols + ' from 
             (
                select store, week, xCount
                from #yt
            ) x
            pivot 
            (
                sum(xCount)
                for week in (' + @cols + ')
            ) p '

execute(@query);

*/

Enter Parameters

Options:
Switch sites:
loading Hold tight while we fetch your results