sql-serversql-server-2005t-sql

Calculate data based on days and weeks in SQL


I have clients they stores data in days or weeks bases. But client has only option to store data either in days or week. See below example

ClientID  StoreID    period      hours
1       10      2010-04-19  8.04
1       10      2010-04-20  6.24
1       10      2010-04-21  8.26
1       20      2010-04-22  7.94
1       20      2010-04-23  22.43
1       20      2010-04-24  22.99
2       5       2010-12-19  130.67
2       5       2010-12-26  159.26
2       5       2011-01-02  113.59
2       5       2011-01-09  12.66
2       8       2011-01-16  22.34
2       8       2011-01-23  11.35

Now I have to sum hours based client id period for last 52 weeks to 27 weeks and 27 weeks to present.

Example:

ClientId =1 from last 52 weeks to 27 weeks total hours = 150
ClientId =1 from last 27 weeks to today total hours = 200

ClientId =2 from last 52 weeks to 27 weeks total hours = 350
ClientId =2 from last 27 weeks to today total hours = 250.

How can I write this in T-SQL?

There is another table for Clients time level like this.

Client   time_level
1       Day
2       Week

Update: We need to find total of hours of storedid based on @clientid


Solution

  • DECLARE @MondayThisWeek DATETIME
    SELECT  @MondayThisWeek = DATEADD(wk,
                                 DATEDIFF(wk, 0, GETDATE()),
                                 0);
    
    DECLARE @ClientId INT;
    SELECT @ClientId = 1;
    
    
    
    SELECT  cd.StoreId,
        SUM(cd.HOURS) AS Hours
    FROM    ClientData cd
    WHERE   cd.Date >= DATEADD(ww, -52, @MondayThisWeek)
        AND cd.Date < DATEADD(ww, -27, @MondayThisWeek)
        AND cd.ClientId = @ClientId 
    GROUP BY cd.StoreId;
    
    SELECT  cd.StoreId,
        SUM(cd.HOURS) AS Hours  
    FROM    ClientData cd
    WHERE   cd.Date >= DATEADD(ww, -27, @MondayThisWeek)
        AND cd.Date < @MondayThisWeek
        AND cd.ClientId = @ClientId
    GROUP BY cd.StoreId;