Skip to content
Advertisement

I’m looking for a right solution to achieve the below scenario in SQL Server

I’ve a result set from a query like this below

Court_id from to Available
7 6:00:00 7:00:00 Yes
7 7:00:00 8:00:00 No
7 8:00:00 9:00:00 Yes
8 6:00:00 7:00:00 Yes
8 7:00:00 8:00:00 Yes
8 8:00:00 9:00:00 No
9 6:00:00 7:00:00 Yes
9 7:00:00 8:00:00 Yes
9 8:00:00 9:00:00 No

How can I achieve in column wise like below from the above result ?

from to 7 8 9
6:00:00 7:00:00 Yes Yes Yes
7:00:00 8:00:00 no Yes Yes
8:00:00 9:00:00 Yes no no

Court_id can change time to time.

I’ve tried the following

CREATE TABLE [testslots](   
    [Court_id] [int] NULL,
    [from]  [nvarchar](10) NULL,
    [to]  [nvarchar](10) NULL,
    [Available] [nvarchar](10) NULL);


INSERT INTO [testslots] ([Court_id] ,[from] ,[to] ,[Available])VALUES (7,'6AM','7AM','Yes');
INSERT INTO [testslots] ([Court_id] ,[from] ,[to] ,[Available])VALUES (7,'7AM','8AM','no');
INSERT INTO [testslots] ([Court_id] ,[from] ,[to] ,[Available])VALUES (7,'8AM','9AM','Yes');
INSERT INTO [testslots] ([Court_id] ,[from] ,[to] ,[Available])VALUES (8,'6AM','7AM','Yes');
INSERT INTO [testslots] ([Court_id] ,[from] ,[to] ,[Available])VALUES (8,'7AM','8AM','Yes');
INSERT INTO [testslots] ([Court_id] ,[from] ,[to] ,[Available])VALUES (8,'8AM','9AM','no');
INSERT INTO [testslots] ([Court_id] ,[from] ,[to] ,[Available])VALUES (9,'6AM','7AM','Yes');
INSERT INTO [testslots] ([Court_id] ,[from] ,[to] ,[Available])VALUES (9,'7AM','8AM','Yes');
INSERT INTO [testslots] ([Court_id] ,[from] ,[to] ,[Available])VALUES (9,'8AM','9AM','no');


DECLARE @cols AS NVARCHAR(MAX),
    @query  AS NVARCHAR(MAX);

SET @cols = STUFF((SELECT distinct ',' + QUOTENAME(c.Court_id) 
            FROM [testslots] c
            FOR XML PATH(''), TYPE
            ).value('.', 'NVARCHAR(MAX)') 
        ,1,1,'')

set @query = 'SELECT [from],[to], ' + @cols + ' from 
            (
                select [from]
                    , [to]
                    , [available]
                from testslots
           ) x
            pivot 
            (
                 max([available])
                for available in (' + @cols + ')
            ) p '

exec sp_executesql @query;

Advertisement

Answer

You are pivoting the wrong columns:

DECLARE @cols nvarchar(max) = STUFF((
            SELECT distinct ',' + QUOTENAME(c.Court_id) 
            FROM [testslots] c
            FOR XML PATH(''), TYPE
            ).value('text()[1]', 'NVARCHAR(MAX)') 
        ,1,LEN(','),'');

DECLARE @query nvarchar(max) = '
SELECT
  [from],[to],
  ' + @cols + '
from 
(
    select [from]
         , [to]
         , Court_id
         , available
    from testslots
) x
pivot 
(
    max([available])
    for Court_id in (' + @cols + ')
) p;
';

exec sp_executesql @query;
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement