Pergunta

I have a table like:

Name | ID | Event
Smith| 1  | 
Smith| 2  | Y
Smith| 3  | 
Jones| 1  | 
Jones| 2  | Y
Jones| 3  | 
Jones| 4  | Y

I'd like to count the number of times an Event has been seen for each person at each point, e.g.:

Name | ID | Event | Event Count
Smith| 1  |       | 0
Smith| 2  | Y     | 1
Smith| 3  |       | 1
Jones| 1  |       | 0
Jones| 2  | Y     | 1
Jones| 3  |       | 1
Jones| 4  | Y     | 2

I'm guessing I can't do this in SQL? If not, can you be very clear how I go about doing this in SAS (or whatever way is appropriate), as I am new to this!

(FYI, this is leading to me being able to differentiate rows that happen before or after each event - i.e. filter by Event = blank, and anything 0 happened before the first event, anything 1 after, etc. There might be an easier way to do this.)

Thanks!

Foi útil?

Solução

If you want to go down the SAS route, it reads data sequentially so is very good at this type of problem

data have;
infile datalines missover;
input Name $ ID  Event $;
datalines;
Smith 1   
Smith 2   Y
Smith 3   
Jones 1   
Jones 2   Y
Jones 3   
Jones 4   Y
;
run;

proc sort data=have;
by name id;
run;

data want;
set have;
by name id;
if first.name then event_count=0;
event_count+(event='Y');
run;

Outras dicas

You could potentially do something like this in a query:

select Name, ID, Event,
    (
        select count(*)
        from MyTable
        where Name = t.Name
            and Event = 'Y'
            and ID <= t.ID
    ) as EventCount
from MyTable t

The correlated subquery will find this count for you, though this is something of a triangular join (SQL Server link, but still applicable), so performance isn't wonderful.

Here is the SQL Fiddle showing the result.

Note that this should work in virtually any RDBMS.

SELECT Name, ID, Event, grpTotal
FROM
  (
    select  Name,
            ID,
            Event,
            @sum := if(@grp = Name,@sum,0) + if(`Event` = 'Y',1,0) as grpTotal,
            @grp := Name
    from    TableName,
            (select @grp := '', @sum := 0) vars
    order   by  Name, ID
  ) s
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top