首页 > 解决方案 > 如何选择具有相同时间顺序的所有值?

问题描述

我正在使用关联的 Game-Id 将玩家所做的所有动作保存在表格中。

执行移动的顺序也被保存。

桌子:

id | move     | order
---+----------+------
 1 | Attack   | 1
 1 | Defense  | 2
 1 | Defense  | 3
 1 | Fly      | 4
 2 | Attack   | 1

例如:在游戏 ID 1 中,他先攻击,防御,防御然后飞行。

我现在想选择所有与我指定的时间顺序相同的游戏 ID。

伪代码

SELECT DISTINCT id FROM Table
WHERE Player 
first Attack
second Defense
third Defense 

例如,即使未指定第四步 Fly,伪代码也会返回 ID 1。

标签: sqlpostgresql

解决方案


假设您的意思是您想要相同的初始动作集,那么我认为这可以满足您的需求:

SELECT id
FROM (SELECT id, ARRAY_AGG(move ORDER BY "order") as moves
      FROM t
      WHERE order <= 3
     ) im
WHERE moves = ARRAY['Attack', 'Defense', 'Defense'];

这只是检查前三个动作。您也可以将其表述为:

SELECT id
FROM (SELECT id, ARRAY_AGG(move ORDER BY "order") as moves
      FROM t
      WHERE order <= CARDINALITY(ARRAY['Attack', 'Defense', 'Defense'])
     ) im
WHERE moves = ARRAY['Attack', 'Defense', 'Defense'];

推荐阅读