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

SQL Query untuk mengembalikan catatan yang dikelompokkan berdasarkan Minggu, Bulan, dan Tahun. Minggu tanpa catatan harus mengembalikan 0

Demo tujuan Saya menggunakan nama Tabel sebagai [DBO].[FACTINTERNETSALES] dan kolom [ORDERDATE]Untuk Anda Kolomnya adalah [CreatedDate].Fyi, Ini dilakukan di SQL Server.

DECLARE @START INT,
        @END INT

SELECT @START   = CAST(CAST(MIN(ORDERDATE) AS DATETIME) AS INT) FROM [DBO].[FACTINTERNETSALES] 
SELECT @END     = CAST(CAST(MAX(ORDERDATE) AS DATETIME) AS INT) FROM [DBO].[FACTINTERNETSALES] 

--SELECT @START,@END

DECLARE @DATEDIM TABLE (ID INT IDENTITY(1,1) PRIMARY KEY, DATED DATETIME)
WHILE @START <= @END
BEGIN
    INSERT INTO @DATEDIM VALUES (CAST(@START AS DATETIME))
    SET @START = @START  + 1 
END

SELECT      LU.WEEK,LU.MONTH,LU.YEAR,ISNULL(MAIN.COUNT,0) [COUNT]
FROM        (
            SELECT      DATEPART(WEEK,DATED) [WEEK],DATEPART(MONTH,DATED) [MONTH],DATEPART(YEAR,DATED) [YEAR] 
            FROM        @DATEDIM
            GROUP BY    DATEPART(WEEK,DATED),DATEPART(MONTH,DATED),DATEPART(YEAR,DATED)) LU
LEFT JOIN
            (
            SELECT  [YEAR],[MONTH],[WEEK],COUNT(*) [COUNT] FROM
            (SELECT DATEPART(YEAR,ORDERDATE) [YEAR],
                    DATEPART(MONTH,ORDERDATE) [MONTH],
                    DATEPART(WEEK,ORDERDATE) [WEEK]
            FROM    [DBO].[FACTINTERNETSALES] ) LUINNER
            GROUP BY [YEAR],[MONTH],[WEEK]) MAIN 
ON
            LU.MONTH = MAIN.MONTH AND
            LU.YEAR = MAIN.YEAR AND
            LU.WEEK = MAIN.WEEK
ORDER BY    LU.YEAR,LU.MONTH,LU.WEEK

Hasil: (Hanya sebagian dari hasil)




  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 Menampilkan Tanggal dalam Format Inggris di SQL Server (T-SQL)

  2. Bagaimana saya bisa mengubah dari mode SQL Server Windows ke mode campuran (SQL Server 2008)?

  3. Izin EXECUTE ditolak - 'aspnet_Roles_RoleExists'

  4. Tidak dapat memasukkan nilai NULL ke kolom 'USERNAME', tabel 'tempdb.dbo.#temptable error

  5. Apa itu @@MAX_PRECISION di SQL Server?