【问题标题】:MySQL Find first and last rows of rows with matching values in the same columnMySQL在同一列中查找具有匹配值的行的第一行和最后一行
【发布时间】:2013-08-14 19:38:16
【问题描述】:

很抱歉这个问题的措辞不好,很难准确地解释我需要什么。

我使用了这个查询:

select * 
from table 
where unique_id in (
  select unique_id from table group by unique_id having count(*) > 1
)

这给了我如下结果:

id    date         unique_id
12    3/3/2013     asdf1
13    3/4/2013     asdf1
14    3/5/2013     asdf1
15    3/6/2013     asdf1
16    3/8/2013     qwer2
17    3/9/2013     qwer2
18    3/10/2013    qwer2
19    3/11/2013    zxcv3
20    3/12/2013    zxcv3
21    2/2/2012     jkl
22    2/3/2012     jkl
22    2/4/2012     jkl
23    2/5/2012     jkl
24    2/5/2012     jkl
25    2/6/2012     jkl
26    2/7/2012     jkl

我希望查询进一步细化这些结果,并将每组匹配的 unique_id 的第一行和最后一行留给我

**在每组匹配的unique_id中,结果总是遵循ID+1和日期+1天的模式。
** 没有此条件的 count(*) > 1 将等于 1 的记录。

所以换句话说,我希望查询只返回:

12 3/3/2013  asdf1
15 3/6/2013  asdf1
16 3/8/2013  qwer2
18 3/10/2013 qwer2
19 3/11/2013 zxcv3
20 3/12/2013 zxcv3
21 2/2/2012 jkl
26 2/7/2012 jkl

谢谢!

【问题讨论】:

  • 你能提供你使用的表的转储吗?
  • 您好,您具体需要表格中的哪些信息?真实表包含敏感信息,但当我在其上运行该查询时,结果与我在那里发布的相同。
  • 你的表能否有一个unique_id的日期对,其中较晚日期的ID列小于较早日期的ID列?
  • 不,它将始终*遵循我发布的模式。 ID + 1 日期 + 1 天和相同的 unique_id 直到有新的 unique_id。
  • 只是导入转储会更容易...没关系,Declan 已经解决了它

标签: mysql group-by match return-value multiple-columns


【解决方案1】:

由于hte ID和日期列的顺序匹配,可以使用如下。

SELECT  id
        ,date
        ,unique_id
FROM    (
        SELECT  min(id) as id
                ,min(date) as date
                ,unique_id
                ,count(id) as rec_count
        from    table
        group by
                unique_id
        union
        SELECT  max(id) as id
                ,max(date) as date
                ,unique_id
                ,count(id) as rec_count
        from    table
        group by
                unique_id
        ) SQ
WHERE   SQ.rec_count > 1 

【讨论】:

  • 对不起,帖子中的错字(我现在已经更正了)。将WHERE 子句更改为WHERE SQ.rec_count > 1
  • 嘿,如果你还在,我怎么能进一步细化查询以返回如下结果:3/3/2013 - 3/6/2013 asdf1 和下一行 3/8/ 2013 - 3/10/2013 qwer2
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-10-03
  • 2013-09-03
  • 1970-01-01
  • 2020-01-28
  • 2018-10-06
  • 1970-01-01
  • 2012-02-16
相关资源
最近更新 更多