开发者

Pivot SQL query - Show Date in column

my current query return the below result

Pivot SQL query - Show Date in column

What I need is I have to display date in column header. I know it have to be done using Pivot

Example: if we want to display month in column header then query will be something like..

SELECT  [January], [February], [March]
FROM    ( SELECT    [Month], SaleAmount
          FROM      Sales
        ) p PIVOT ( SUM(SaleAmount)
                    FOR [Month] 
                      IN ([January],[February],[March])
                  ) AS pvt

and I think my resultant query should be look like Pivot ( (Price) FOR [DateVal] IN (What will be here?) ) here is what resultant column should be like

Pivot SQL query - Show Date in column

Note: in the result set currently it show December month data, but it can be any month.

Thank开发者_JAVA百科s for your help...


Update 4 Ok, now that you posted all your query, and following your comments, you should try this:

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)=@year AND MONTH(occdate)=@month AND packageid=@packageID 
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], '+@Dates+'
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 ('+@Dates+') ) AS PT'

EXEC(@Query)
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜