SQLite-按ID分组的值的出现次数

问题描述 投票:1回答:1

很抱歉,如果有人问过这个问题,但是也许我不熟悉该语言来询问我想要的东西,我浏览了许多其他问题,但似乎并没有找到什么可行的方法。

我正在使用用于交易纸牌游戏的工具,卡片组是纸牌列表,我有一个将deckId映射到cardId的表

给出示例(未显示行号)

deckId| cardId
-----------
1  | 321
1  | 50
1  | 100
1  | 125
2  | 321
2  | 50
2  | 99
2  | 87
3  | 50
3  | 12
3  | 5
3  | 47
4  | 999
4  | 998
4  | 997
4  | 996

我要查询的是每个卡座,在一个以上卡座中显示多少张卡片。

deckId  |  count(cardId)
--------------------
1  | 2 // 321 and 50 appear in both deckId=1 and deckId=2
2  | 2 // 321 and 50 appear in both deckId=1 and deckId=2
3  | 1 // 50 appears in deckId=2 and deckId=3
4  | 0 // none of the cards in deckId=4 appear in any other decks

我已经尝试过

SELECT deckId, COUNT(cardId)
FROM table
GROUP BY deckId

但是它只是给我(因为每个卡座有4张卡):

deckId  | count(cardId)
-----------------------
1 | 4
2 | 4
3 | 4
4 | 4

所以我如何查询每个卡座,有多少张“普通”卡?

sql sqlite group-by count
1个回答
0
投票

您可以使用窗口函数和聚合:

select 
    deckId,
    sum(case when cnt > 1 then 1 else 0 end) cnt
from (
    select deckId, count(*) over(partition by cardId) cnt
    from mytable 
) t
group by deckId

Demo on DB Fiddle

deckId |碳纳米管:----- | -:1 | 22 | 23 | 1个4 | 0
© www.soinside.com 2019 - 2024. All rights reserved.