sql >> Database >  >> RDS >> Sqlserver

Pivot SQL-query - Datum in kolom weergeven

Update 4 Oké, nu je al je vragen hebt geplaatst en je opmerkingen hebt gevolgd, zou je dit moeten proberen:

DECLARE @FirstDay SMALLDATETIME
SELECT @FirstDay = CONVERT(SMALLDATETIME, (@year + '-' + @month + '-01')); 

WITH Dates AS  
(
  SELECT @FirstDay AS DateVal 
  UNION ALL 
  SELECT DATEADD(d, 1, DateVal) AS DateVal 
  FROM Dates 
  WHERE DATEADD(d, 1, DateVal) < DATEADD(m, 1, @FirstDay)
)

SELECT * INTO #Dates FROM Dates

DECLARE @hotelID INT, @packageID INT, @year VARCHAR(4), @Dates VARCHAR(1000), @month VARCHAR(2), @Query VARCHAR(MAX)
SELECT @hotelID=248, @packageID=76, @year='2010', @month='12',@Dates=''

SELECT co.*,wb.Name,rc.HotelName 
INTO #HotelData
FROM RCompetitorOccupancy co 
INNER JOIN websites wb ON wb.websiteid=co.websiteid
INNER JOIN RoomCompetitor rc ON rc.competitorid=co.competitorid
WHERE YEAR(occDate)[email protected] AND MONTH(occdate)[email protected] AND [email protected] 
AND roomTypeid IN (SELECT roomtypeid FROM CompetitorRoomType WHERE DESCRIPTION=119)

SELECT @Dates = @Dates + '[' + CAST(DATEPART(DAY,DateVal) AS VARCHAR(2)) + '-' + LEFT(DATENAME(MONTH,DateVal),3)+ '],'
FROM #Dates
GROUP BY Dateval

SET @Dates = LEFT(@Dates,LEN(@Dates)-1)

SET @Query = '
SELECT roomtypeid, description, [Name], [HotelName], '[email protected]+'
FROM (  SELECT  HD.roomtypeid, HD.description, HD.[Name], HD.[HotelName], HD.Price, 
                CAST(DATEPART(DAY,DateVal) AS VARCHAR(2)) + ''-'' + LEFT(DATENAME(MONTH,DateVal),3) [Date]
        FROM #Dates D
        LEFT JOIN #HotelData HD
        ON D.DateVal = HD.OccDate) T
PIVOT ( SUM(Price) FOR [Date] IN ('[email protected]+') ) AS PT'

EXEC(@Query)



  1. mysql - FOUT 1064 (42000) bij gebruik van trefwoorden als kolomnaam

  2. MySQL select sum met group by en lege waarden

  3. Is het vergelijken van strings in MySQL kwetsbaar voor timing-aanvallen?

  4. Ik wil Zoek een specifieke waarde in alle kolommen van alle tabellen in orakel 11g