很抱歉,如果有人问过这个问题,但是也许我不熟悉该语言来询问我想要的东西,我浏览了许多其他问题,但似乎并没有找到什么可行的方法。
我正在使用用于交易纸牌游戏的工具,卡片组是纸牌列表,我有一个将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
所以我如何查询每个卡座,有多少张“普通”卡?
您可以使用窗口函数和聚合:
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
deckId |碳纳米管:----- | -:1 | 22 | 23 | 1个4 | 0