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

Hitung jumlah catatan untuk setiap tanggal antara 2 tanggal

Memperbaiki jawaban Dale K, saya sarankan Anda menggunakan tabel penghitungan atau fungsi, karena ini biasanya lebih berkinerja.

Saya telah menggunakan Itzik Ben-Gan yang terkenal di bawah ini:

DECLARE @StartDate date = '2020-11-01', @EndDate date = '2021-02-22';

  WITH
    L0 AS ( SELECT 1 AS c 
            FROM (VALUES(1),(1),(1),(1),(1),(1),(1),(1),
                        (1),(1),(1),(1),(1),(1),(1),(1)) AS D(c) ),
    L1 AS ( SELECT 1 AS c FROM L0 AS A CROSS JOIN L0 AS B ),
    L2 AS ( SELECT 1 AS c FROM L1 AS A CROSS JOIN L1 AS B ),
    Nums AS ( SELECT ROW_NUMBER() OVER(ORDER BY (SELECT NULL)) AS rownum
              FROM L2 )
    Date_Range_T (d_range) AS (
      SELECT TOP(DATEDIFF(day, @StartDate, @EndDate) + 1)
          DATEADD(day, rownum - 1, @StartDate) AS d_range,
          DATEADD(day, rownum, @StartDate) AS d_rangeNext
      FROM Nums
    )
SELECT d_range, COUNT(Id) AS Total 
FROM Date_Range_T 
LEFT JOIN tbl_Support_Requests R
    ON R.CreatedDate >= T.d_range AND R.CreatedDate < T.d_rangeNext
GROUP BY d_range
ORDER BY d_range ASC


  1. Database
  2.   
  3. Mysql
  4.   
  5. Oracle
  6.   
  7. Sqlserver
  8.   
  9. PostgreSQL
  10.   
  11. Access
  12.   
  13. SQLite
  14.   
  15. MariaDB
  1. Cara Menonaktifkan Batasan Kunci Asing di SQL Server (Contoh T-SQL)

  2. Webinar :Pelacakan Kemajuan Kueri di SQL Server

  3. Praktik Terbaik Pemulihan Bencana Microsoft SQL Server

  4. Bekerja dengan Data Salesforce.com di Layanan Pelaporan SQL Server

  5. ROUND() Contoh di SQL Server