【问题标题】:How to get duplicate rows with group by and order by?如何使用 group by 和 order by 获取重复行?
【发布时间】:2019-05-06 19:46:18
【问题描述】:

我想用 order by 获取重复的行,我正在尝试这种方式:

SELECT utc_id, utc_utiid, utc_comid, utc_recomendacoes FROM
( SELECT * FROM utilizador_competencia ORDER BY utc_recomendacoes DESC)
as sub GROUP BY utc_utiid, utc_comid HAVING COUNT(*) > 1

结果:

+--------+-----------+-----------+-------------------+
| utc_id | utc_utiid | utc_comid | utc_recomendacoes |
+--------+-----------+-----------+-------------------+
|     14 |         2 |       397 |                54 |
+--------+-----------+-----------+-------------------+

这里是重复行,但我想获取 utc_id -> 207 而不是 utc_ic -> 14:

+--------+-----------+-----------+-------------------+
| utc_id | utc_utiid | utc_comid | utc_recomendacoes |
+--------+-----------+-----------+-------------------+
|     14 |         2 |       397 |                54 |
|    207 |         2 |       397 |                87 |
+--------+-----------+-----------+-------------------+

【问题讨论】:

  • 您不能在子查询中使用 ORDER BY。你必须在外面使用它。
  • 我认为您的子查询中不能有 ORDER BY。加上 ORDER BY 不会做任何事情来消除重复。您可能只需完全删除 ORDER BY 即可获得所需的内容。但我不知道无论如何都需要这个子查询。这个查询会抛出什么错误?
  • 这是什么意思:“我想用 order by 获取重复的行,我正在尝试这种方式”?样本数据和期望的结果真的很有帮助。
  • @GordonLinoff 我已经更新了问题。
  • 为什么你更喜欢 207 而不是 14?也许你想要MAX()?查看添加的标签。

标签: mysql sql mariadb greatest-n-per-group


【解决方案1】:

我猜你打算:

select c.*
from utilizador_competencia c
where exists (select 1
              from utilizador_competencia c2
              where c2.utc_utiid = c.utc_utiid and
                    c2.utc_comid = c.utc_comid and
                    c2.utc_id <> c.utc_id
             )
order by c.utc_id, c.utc_id, c.utc_recomendacoes desc;

【讨论】:

  • 这给了你所有的副本?不只是“最后一个”?
【解决方案2】:
SELECT t.utc_id, t.utc_utiid, t.utc_comid, t.utc_recomendacoes
FROM
( SELECT utc_utiid, utc_comid 
  FROM utilizador_competencia 
  GROUP BY utc_utiid, utc_comid HAVING COUNT(*) > 1) d
INNER JOIN utilizador_competencia t
ON d.utc_utiid=t.utc_utiid
AND d.utc_comid=t.utc_comid 
ORDER BY t.utc_recomendacoes DESC;

这是你想要的吗?

【讨论】:

  • 不,请查看问题的更新,谢谢。
【解决方案3】:

对可见结果应用 order by .. 子查询只是一个数据集 .. 所以子查询的 order by 是无用的
将订单移出子查询

SELECT utc_id, utc_utiid, utc_comid, utc_recomendacoes 
FROM ( 
    SELECT * 
    FROM utilizador_competencia 
    ) as sub 
GROUP BY utc_utiid, utc_comid  
HAVING COUNT(*) > 1
ORDER BY utc_recomendacoes DESC

根据您的评论

SELECT utc_id, utc_utiid, utc_comid, utc_recomendacoes 
FROM utilizador_competencia 
GROUP BY utc_utiid, utc_comid  
HAVING COUNT(*) > 1
ORDER BY utc_recomendacoes DESC

【讨论】:

  • 嗯..我想用“utc_recomendacoes DESC”得到重复的行。也就是在 group by 之前用 DESC 或 ASC 选择重复的行。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-09-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多