简体   繁体   中英

SQL Query for Count value from the latest date

I need to have a query that returns the ff:

  1. Count from the latest Date in each Name
  2. If the value of Count from the latest Date is -1 then it will return the count of the Date before the latest Date
  3. If the value of Count from the latest Date is -1 and the other Date is -1. Then return 0
  4. 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

select A.name, isnull(T.[Count], 0) as [Count]
from (select distinct T.name from table1 as T) as A
    outer apply 
    (
        select top 1 T.[Count]
        from table1 as T
        where T.name = A.name and T.[Count] <> -1 
        order by T.[date] desc
    ) as T
order by A.name asc

UPDATE : for SQL 2000 you can use query like this

SQL FIDDLE EXAMPLE for SQL 2000

select A.name, isnull(T1.[Count], 0) as [Count]
from 
(
    select T.name, max(case when T.[Count] <> -1 then T.[date] else null end) as [date]
    from table1 as T
    group by T.name
) as A
    left outer join table1 as T1 on T1.name = A.name and T1.[date] = A.[date]

but it relies on suggestion that you have unique constraint on name, [date] columns

an other one

Select * from
(
Select Test.name,[Count]
from TEST
Join(
Select name, MAX(Date) as Date from TEST  
where [Count]<>-1
Group by Name) a
on a.Name=test.Name and a.Date=Test.Date
UNION 
Select Distinct name,0 from test o where not Exists(Select * from test where name=o.Name and [count]<>-1)
) res
order by Name

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM