alexakarpov
alexakarpov

Reputation: 1920

SQL pivot or self-join for this?

I've a table, Events, which has 2 columns matter) - entityId : string - eventId : int

a presence of a row ("foo", 42) means that an event with id 42 happened on to the entity "foo".

what I want to do is figure out, from the table, which event id were NOT registered for which entities. E.g. the data:

"foo", 1

"foo", 2

"foo", 3

"bar", 1

"bar", 2

"baz", 3

should produce an answer of this kind:

.... | 1 | 2 | 3

foo| y | y |y

bar| y | y |n

baz| n | n |y

I've looked around and saw references to pivots and joins floating around. Any suggestions on the best course of actions? Thanks!

Upvotes: 0

Views: 535

Answers (1)

alexakarpov
alexakarpov

Reputation: 1920

ok I think this is what I need:

 SELECT
        entityId,
        COUNTIF(eventId == 1) AS event1_count,
        COUNTIF(event_id == 2) AS event2_count,
        COUNTIF(event_id == 3) AS event3_count,
        COUNTIF(event_id == 4) AS event4_count
    FROM data
    GROUP BY entityId;

Upvotes: 1

Related Questions