Search code examples
sqlsql-serversql-server-2000

SQL Server 2000 Query of total value and value from max date


I have this RoomTable with value

SID   Room   Date        APhase   BPhase   ACount  BCount
1     One    10/28/2012  4        5         3       6
2     One    10/29/2012  2        3        -1      -1
3     One    10/30/2012  4        5         7      -1
4     Two    10/28/2012  8        3         2       3
5     Two    10/30/2012  3        5         4       6
6     Three  10/29/2012  5        8         2      -1
7     Three  10/30/2012  5        6        -1       4
8     Four   10/29/2012  6        2        -1      -1
9     Four   10/30/2012  5        8        -1      -1

What I want is to return the following:

  1. Total sum of APhase and BPhase of each Room.
  2. Value of ACount and BCount from max date of each Room
  3. If ACount value is -1 then use the previous date. Same as BCount.
  4. If ACount value is -1 and the previous date is -1 and so on. Then use 0. Same as BCount.

I can get the query of number 1 with this query

SELECT Room, sum(APhase) as TotalAPhase, sum(BPhase) as TotalBPhase 
FROM RoomTable 
WHERE Date between '10/28/2012' and '10/30/2012'
group by Room
order by Room

But I'm confused on how to include the number 2-4 query.

This is the output I want

Room  TotalAPhase  TotalBPhase  ACount   BCount
One   10           13           7        6
Two   11           8            4        6
Three 10           13           2        4
Four  11           10           0        0

Any ideas will be much appreciated. Thanks.


Solution

  • Hope this works for your case:

    SELECT 
    Room
    ,SUM(APhase) AS TotalAPhase
    ,SUM(BPhase) AS TotalBPhase 
    ,ISNULL((    SELECT TOP 1 RT1.ACount 
                 FROM RoomTable RT1 
                 WHERE RT1.Room = RT.Room 
                    AND RT1.ACount != -1
                 ORDER BY RT1.Date DESC
    ), 0) AS ACount
    ,ISNULL((   SELECT TOP 1 RT2.BCount 
                FROM RoomTable RT2
                WHERE RT2.Room = RT.Room 
                   AND RT2.BCount != -1
                ORDER BY RT2.Date DESC
    ), 0) AS BCount
    
    FROM RoomTable RT
    --WHERE Date between '10/28/2012' and '10/30/2012'
    GROUP BY Room
    ORDER BY Room
    

    I am not sure if you really need that where clause so I commented it out. And the value of TotalBPhase for Room Three on your result table should be 14, as can be seen from this SQL Fiddle demo.