0

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

  1. 从每个名称中的最新日期开始计数
  2. 如果 Count from the latest Date 的值为 -1,那么它将返回最新 Date 之前的 Date 的计数
  3. 如果最新日期的计数值为-1,另一个日期为-1。然后返回 0
  4. 如果最新日期的计数值为 -1 且没有该名称的其他日期。然后返回 0

示例表:

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。

4

2 回答 2

5

试试这个

SQL 提琴示例

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 2000 的SQL FIDDLE 示例

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

于 2012-11-02T07:39:30.787 回答
1

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
于 2012-11-02T07:53:42.533 回答