0
votes

Sous-requête corrélée au nombre de numéros de rangée

J'ai une table comme suit et ce que je veux, c'est utiliser obtenir la ligne initiale avec le moins d'identifiant de chaque groupe UID.

La table est la suivante P>

_id  uid  type  cnt
5     a    aaa   1
2     b    bbb   2


0 commentaires

3 Réponses :


1
votes

Vous pouvez essayer ceci:

SELECT t1.*, t2.cnt
FROM table t1 INNER JOIN (
  SELECT MIN(_id) AS id, COUNT(_id) AS cnt
  FROM table 
  WHERE type IN ('aaa','bbb')
  GROUP BY uid
) t2 ON t1._id = t2.id
ORDER BY t1.uid


0 commentaires

1
votes

Si vous exécutez MySQL 8.0, vous pouvez simplement utiliser les fonctions de fenêtre pour cela:

select _id, uid, type, cnt
from (
    select 
        t.*, 
        count(*) over(partition by uid) cnt,
        row_number() over(partition by uid order by _id) rn
    from mytable t
    where type in ('aaa', 'bbb')
) t
where rn = 1


0 commentaires

1
votes

Vous pouvez le faire sans subquiery. Dans MySQL 8+, vous pouvez utiliser cette logique:

SELECT MIN(_id) as _id, uid,
       SUBSTRING_INDEX(GROUP_CONCAT(type ORDER BY _id), ',', 1) as type,
       COUNT(*) as cnt
FROM table 
WHERE type IN ('aaa', 'bbb')
GROUP BY uid;


0 commentaires