Sqlserver
 sql >> Teknologi Basis Data >  >> RDS >> Sqlserver

Kueri Pivot SQL - Tampilkan Tanggal di kolom

Perbarui 4 Oke, sekarang setelah Anda memposting semua pertanyaan Anda, dan mengikuti komentar Anda, Anda harus mencoba ini:

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. Database
  2.   
  3. Mysql
  4.   
  5. Oracle
  6.   
  7. Sqlserver
  8.   
  9. PostgreSQL
  10.   
  11. Access
  12.   
  13. SQLite
  14.   
  15. MariaDB
  1. Maks dalam jangka waktu dengan duplikat tanggal

  2. TSQL Pilih dari Tabel Berbeda berdasarkan nilai KASUS

  3. Aktifkan Pencarian Teks Lengkap di Tampilan dengan Inner Join

  4. Mendapatkan operasi beberapa langkah menghasilkan kesalahan. Periksa setiap nilai status. kesalahan menggunakan ADO dengan SQL server 2008

  5. sp_executesql dengan pernyataan 'IN'