sql >> Database >  >> RDS >> Sqlserver

Dynamische kolommen retourneren van gegroepeerde waarden in SQL Server (opgeslagen procedure)

Probeer voor Case 1 dit:

--Creating Test tables
create table #activity
(
    ActivityId TINYINT,
    ActivityName VARCHAR(20)
)

create table #date
(
    [Date] DATE,
    ActivityId TINYINT
)

INSERT INTO #activity VALUES(1,'Activity 1')
INSERT INTO #activity VALUES(2,'Activity 2')
INSERT INTO #activity VALUES(3,'Activity 3')

INSERT INTO #date VALUES('2015-05-01',1)
INSERT INTO #date VALUES('2015-05-01',1)
INSERT INTO #date VALUES('2015-05-02',2)
INSERT INTO #date VALUES('2015-05-03',3)


DECLARE @activities NVARCHAR(MAX)
DECLARE @stmt NVARCHAR(MAX)

SET  @activities = ''
SET  @stmt = ''

--Get List of Activities
SELECT  @activities = @activities + ',[' + ActivityName + ']'
FROM    #activity

SET @activities = RIGHT(@activities, LEN(@activities)-1) --Remove Leading Comma

--Build PIVOT Statement
SET @stmt = 'SELECT  [Date],' + @activities + '
            FROM    (SELECT d.[Date], a.ActivityName
                     FROM   #date d
                            INNER JOIN #activity a ON d.ActivityId = a.ActivityId) tab
                    PIVOT (COUNT(ActivityName) FOR ActivityName IN (' + @activities + ')) AS NumberOfActivities'

--Execute
EXEC sp_executesql @stmt

--CleanUp
DROP TABLE #activity
DROP TABLE #date


  1. Npgsql-verbinding met ssl-certificaten in .net core web api

  2. Een geheel getal van een db-kolom converteren naar tekst in oracle

  3. SQL QUERY - Hoe het laatste kind van een tabel te extraheren?

  4. onjuist doden van mysqld - start nu niet