2010-09-21 57 views
0

我有一个表遵循计数有状态的FoxPro

id name date 
1 a 08/09/2003 
2 b 02/03/2003 
3 c 10/08/2004 
4 c 25/08/2007 
5 a 01/01/2008 

我想指望数据库。 与见下表与结果如下:

2003 = 2 
2004 = 1 
2007 = 0 because c has in 2004-year 
2008 = 0 because a has in 2003-year 

回答

1

首先,获取名称和它出现在最早的一年:

select name, min(year(date)) as year from table 
group by name into cursor temp 

然后从一年之内获得数:

select count(table.name) 
from table join temp on table.name = temp.name 
and year(table.date) = temp.year 
+0

非常感谢你。 – maolddv 2010-09-21 10:01:39

1

我可能正在解决一个不同的问题,但是这个代码给出了在往年没有出现的名字的每年的计数:

*-- Get the firstyear for each name 
Select Name, Min(Year(Date)) As firstyear ; 
    From table1; 
    Group By Name Into Cursor temp1 

*-- Get the year of the date for each entry 
Select Id, Name, Year(Date) As yr From table1 Into Cursor temp2 

*-- Identify those rows that appear for the first time 
Select temp2.*, temp1.firstyear, Iif(temp2.yr = temp1.firstyear, 1, 0) As countme ; 
    FROM temp2 INNER Join temp1 ; 
    ON temp2.Name = temp1.Name Into Cursor temp3 

*-- Add up the "CountMe" fields to get the sum. 
Select yr, Sum(countme) From temp3 Group By yr 
+0

谢谢!但它错误“进入游标”。无法完成。 – maolddv 2010-09-22 02:39:19

+0

谢谢!我确实做到了成功。 – maolddv 2010-09-22 06:53:13

0

* /第一,得到每名基础的第一年,他们有一个交易 */...为除了总交易此人无论 年..恩* /的:您的“一”和“c”的人两个重叠

SELECT ; 
     YT.Name,; 
     MIN(YEAR(YT.DATE)) as FirstYear,; 
     COUNT(*) as TotalPerName; 
    FROM ; 
     YourTable YT; 
    GROUP BY ; 
     1; 
    INTO ; 
     CURSOR C_ByNameTotals 

* /现在你已经根据每个人的第一年,其总 * /条目无论一年的总和,获得一年总和总计有一个给定年份的 * /条目....然后所有原始年份可能性的联盟 * /不在C_ByNameTotals中集合。 (因此你的2007年和2008年)

SELECT; 
     FirstYear as FinalYear,; 
     SUM(TotalPerName) as YrCount; 
    FROM ; 
     C_ByNameTotals; 
    GROUP BY ; 
     1; 
    INTO ; 
     CURSOR C_FinalResults; 
UNION; 
SELECT DISTINCT; 
     YEAR(Date) as FinalYear,; 
     0 as YrCount; 
    FROM ; 
     YourTable ; 
    WHERE ; 
     YEAR(Date) NOT IN ; 
      (select FirstYear FROM C_ByNameTotals)