简体   繁体   中英

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. Eg 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!

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;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM