Skip to content
Advertisement

SQLite 3.24 – Counting occurrences of value grouped by id without using window functions

Apologies if this has been asked, but maybe I’m not familiar with the language to ask for what I want, and I looked through dozens of other questions but don’t seem to be finding what works.

I’m working on a tool for a trading card game, a deck is a list of cards, I have a table mapping deckId to cardId

Given the example (rowid not shown)

What I am trying to query is for each deck, how many cards does it have that appear in more than 1 deck.

I’ve tried

but it just gives me (because each deck has 4 cards):

So how do I query for each deck, how many “common” cards does it have? (window functions were suggested, but i’m forced to use SQLite version 3.24 before window functions are implemented)

Advertisement

Answer

You can use window functions and aggregation:

Demo on DB Fiddle:

deckId | cnt
:----- | --:
1      |   2
2      |   2
3      |   1
4      |   0

In versions of SQLite that do not support window functions, you can emulate the window count with a subquery:

User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement