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

Permintaan SQL Server - hitung ketersediaan kamar

Coba kueri di bawah

DECLARE @Reservation TABLE ( BookDate DATE, ROOMS INT)
 INSERT INTO @Reservation VALUES 
('1-Jul-2015',30 ), 
('2-Jul-2015',30 ),
('3-Jul-2015',30 ),
('5-Jul-2015',28 ),
('6-Jul-2015',28 ),
('7-Jul-2015',28 ),
('8-Jul-2015',30 ),
('9-Jul-2015',30 ),
('10-Jul-2015',26 ),
('11-Jul-2015',28 ),
('12-Jul-2015',28 )


    ;WITH
    cte AS (
        select ROW_NUMBER() OVER(ORDER BY BookDate) AS RowNumber,
        [ROOMS], BookDate FROM @Reservation
    ),
    cte2 as (
        SELECT TOP 1 RowNumber, 1 as GroupNumber, [ROOMS], BookDate FROM cte ORDER BY RowNumber
        UNION ALL
        SELECT c1.RowNumber,
            CASE WHEN c2.[ROOMS] <> c1.[ROOMS] then c2.GroupNumber + 1 ELSE c2.GroupNumber END AS  GroupNumber, c1.[ROOMS], c1.BookDate 
        FROM cte2 c2 join cte c1 on c1.RowNumber = c2.RowNumber + 1     
    )
    SELECT Start_Date, End_Date, Rooms
    FROM
    (   SELECT MIN(BookDate) AS START_DATE, MAX(BookDate) AS END_DATE ,ROOMS, GroupNumber
        FROM cte2
        GROUP BY  ROOMS ,GroupNumber
    ) a

Demo SQLFiddler



  1. Database
  2.   
  3. Mysql
  4.   
  5. Oracle
  6.   
  7. Sqlserver
  8.   
  9. PostgreSQL
  10.   
  11. Access
  12.   
  13. SQLite
  14.   
  15. MariaDB
  1. Apa gunanya menyertakan pernyataan tertentu dalam suatu transaksi?

  2. Tidak dapat membuat baris berukuran 8064 yang lebih besar dari ukuran baris yang diizinkan yaitu 8060

  3. Pembaruan ad hoc untuk katalog sistem tidak diperbolehkan

  4. Apakah mungkin untuk memilih data server sql menggunakan posisi ordinal kolom

  5. Pernyataan Kasus dalam SQL menggunakan Suka