I need to have a query that returns the ff:
- Count from the latest Date in each Name
- If the value of Count from the latest Date is -1 then it will return the count of the Date before the latest Date
- If the value of Count from the latest Date is -1 and the other Date is -1. Then return 0
- If the value of Count from the latest Date is -1 and no other Date of that Name. Then return 0
Example Table:
ID Name Date Count
1 Adj 09/29/2012 2
2 Adj 09/30/2012 4
3 Ped 09/29/2012 -1
4 Ped 09/30/2012 5
5 Mel 09/29/2012 3
6 Mel 09/30/2012 -1
7 Rod 09/30/2012 7
8 Ney 09/30/2012 -1
9 Jin 09/29/2012 -1
10 Jin 09/30/2012 -1
Desired Output:
Name Count
Adj 4
Ped 5
Mel 3
Rod 7
Ney 0
Jin 0
I am very confused on how to approach this in SQL since I only knew simple query.
Any idea on how to make a query for this? Thanks.
Btw, I’m sorry I forgot to include this. I am using SQL Server 2000.
Try this
SQL FIDDLE EXAMPLE
UPDATE: for SQL 2000 you can use query like this
SQL FIDDLE EXAMPLE for SQL 2000
but it relies on suggestion that you have unique constraint on
name, [date]columns