sql >> Databasteknik >  >> RDS >> Sqlserver

Hur man returnerar dynamiska kolumner från grupperade värden i SQL Server (Lagrad procedur)

För fall 1 prova detta:

--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. PHP – Det är inte säkert att lita på systemets tidszoninställningar

  2. Är COUNT(rovid) snabbare än COUNT(*)?

  3. Hantera e-postbekräftelse under registrering i kolv

  4. Hur man får en rad-för-rad MySQL-resultatuppsättning i python