sql >> Database teknologi >  >> RDS >> Sqlserver

Sådan returneres dynamiske kolonner fra grupperede værdier i SQL Server (lagret procedure)

For tilfælde 1 prøv dette:

--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. MySQL-vægtet gennemsnit i en enkelt forespørgsel

  2. 5 måder at liste midlertidige tabeller ved hjælp af T-SQL

  3. MySQL for at få tællingen af ​​rækker, der falder på en dato for hver dag i en måned

  4. SQL-fejl:1064, SQLState:42000 i @Query - JPA, MySQL, Hibernate