sql >> Database >  >> RDS >> Sqlserver

SQL-query om records te retourneren die zijn gegroepeerd op week, maand en jaar. Weken zonder records zouden 0 . moeten retourneren

Doel van de demo Ik gebruik de tabelnaam als [DBO].[FACTINTERNETSALES] en de kolom [ORDERDATE]Voor jou is de kolom [CreatedDate]. Ter info, dit gebeurt in 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

Resultaat: (Slechts een deel van het resultaat)




  1. Hoe SQLite-resultaten op te maken als een tabel

  2. Slaap langzaam om Postgres-verbinding te verkrijgen

  3. Oracle XE 11g de XE-database is niet gevonden

  4. Wat is de snelste manier om een ​​grote mysql-databaseback-up te importeren?