sql >> Database teknologi >  >> RDS >> Sqlserver

SQL Server til at tælle, hvor mange gange en værdi vises mellem flere datointervaller og sammenligne med tidligere uger

Jeg tror, ​​at dette kan give dig det, du leder efter:

;WITH 
weekcounts AS (
    SELECT Time_Stamp, Emp_ID, [Balance], ROUND(CONVERT(FLOAT,[Balance]) / 60.0,2) AS [Hours], DATEPART(week, Time_Stamp) AS int_week FROM newSampleData
)

,counts AS (
    SELECT Emp_ID, int_week, 1 AS int_count
    FROM weekcounts
    WHERE ([Hours] >= 7.5)
    UNION ALL
    SELECT weekcounts.Emp_ID, weekcounts.int_week, 1 AS int_count
    FROM weekcounts
        INNER JOIN counts
            ON weekcounts.Emp_ID = counts.Emp_ID
            AND (weekcounts.int_week - 1) = counts.int_week
            AND ([Hours] >= 7.5)
)

,countsagg AS (
    SELECT Emp_ID, int_week, SUM(int_count) AS int_count
    FROM counts
    GROUP BY Emp_ID, int_week
)

SELECT Emp_ID, 
       ISNULL([29],0) AS [week 29],
       ISNULL([30],0) AS [week 30],
       ISNULL([31],0) AS [week 31],
       ISNULL([32],0) AS [week 32],
       ISNULL([33],0) AS [week 33] 
FROM countsagg
PIVOT (MAX(int_count) FOR int_week IN ([29],[30],[31],[32],[33])) piv

Også hvis Balance er en varchar, laver du flere konverteringer end nødvendigt i din angivne kode. Dette vil give resultatet i timevis med mindre kode:

ROUND(CONVERT(FLOAT,[Balance]) / 60.0,2)



  1. Eventplanlægger i PostgreSQL?

  2. Hvorfor tillader MySQL at opdatere en NOT NULL kolonne til NULL?

  3. Indtast stort indhold til Oracle-databasen

  4. Sådan ændres tabel tilføje kolonne orakel