sql >> データベース >  >> RDS >> Sqlserver

ピボット SQL クエリ - 列に日付を表​​示

    アップデート 4 すべてのクエリを投稿したので、コメントに従って、これを試してください:

    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. Entity Frameworkを使用してSql Server Expressで次のシーケンス番号を取得するには?

    2. UTF8文字がdatatablesおよびyadcfで正しく表示されない

    3. フルテキスト インデックスに対する混合クエリ

    4. PostgreSQLとMySQL