从最新日期开始的SQL查询计数值

时间:2012-11-02 07:33:49

标签: sql sql-server

我需要一个返回ff的查询:

  1. 从每个姓名中的最新日期算起
  2. 如果最新日期的Count值为-1,那么它将返回最晚日期之前的日期计数
  3. 如果最新日期的Count值为-1而另一个日期为-1。然后返回0
  4. 如果最新日期的Count值为-1且该名称没有其他日期。然后返回0
  5. 示例表:

    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
    

    期望的输出:

    Name   Count
    Adj    4
    Ped    5
    Mel    3
    Rod    7
    Ney    0
    Jin    0
    

    我对如何在SQL中处理这个问题感到很困惑,因为我只知道简单的查询。

    有关如何对此进行查询的任何想法?感谢。

    是的,对不起,我忘了把它包括在内。我正在使用SQL Server 2000。

2 个答案:

答案 0 :(得分:5)

试试这个

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

更新:对于SQL 2000,您可以使用此类查询

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]

但它依赖于您对name, [date]

有唯一约束的建议

答案 1 :(得分:1)

另一个

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