Forum Discussion

leerjones85's avatar
leerjones85
Copper Contributor
Nov 11, 2024

Help with SQL Code

Hi, I have a table called FACT_DELAYS which contains the following columns: ID, START_DATE, END_DATE, FILTERED_MINUTES If an event is still active then END_DATE IS NULL. Example Data: 1, 20/10/2...
  • rodgerkong's avatar
    Nov 12, 2024
    1. Use table value constructor OR UNION to build a date list of past 7 days.
    2. Use OUTER APPLY pass the date into inner query as parameter.
    3. COUNT rows that fit conditions and returns the result to main query.
    CREATE TABLE #FACT_DELAYS
    (
    	[ID] int,
    	[START_DATE] date, 
    	[END_DATE] date, 
    	[FILTERED_MINUTES] int
    )
    
    INSERT INTO #FACT_DELAYS
    VALUES
     (1, '2024-10-20', null, 25)
    ,(2, '2024-11-07', null, 67)
    ,(3, '2023-08-02', '2024-11-10', 43)
    ,(4, '2022-01-01', null, 20)
    --,(5, '2024-11-09', null, 21)
    
    SELECT DS.D AS [DATE], ISNULL(FN.N, 0) AS [COUNT(FILTERED_MINUTES)] FROM 
    (VALUES
    	 ( CAST( GETDATE() AS DATE) )
    	,( CAST( DATEADD( DAY, -1, GETDATE() ) AS DATE) )
    	,( CAST( DATEADD( DAY, -2, GETDATE() ) AS DATE) )
    	,( CAST( DATEADD( DAY, -3, GETDATE() ) AS DATE) )
    	,( CAST( DATEADD( DAY, -4, GETDATE() ) AS DATE) )
    	,( CAST( DATEADD( DAY, -5, GETDATE() ) AS DATE) )
    	,( CAST( DATEADD( DAY, -6, GETDATE() ) AS DATE) )
    	--,( CAST( DATEADD( DAY, -7, GETDATE() ) AS DATE) )
    ) AS DS(D)
    OUTER APPLY
    (
    	SELECT COUNT([FILTERED_MINUTES]) AS N FROM #FACT_DELAYS F
    	WHERE F.START_DATE <= DS.D AND (F.END_DATE IS NULL OR F.END_DATE >= DS.D)
    )FN
    ORDER BY DS.D DESC
    
    DROP TABLE IF EXISTS #FACT_DELAYS

     

Resources