【问题标题】:SQL Server : getting multiple min/max values from one querySQL Server:从一个查询中获取多个最小值/最大值
【发布时间】:2018-10-21 01:36:33
【问题描述】:

我在 SQL Server 中有类似以下的数据。我想查询单个表的类别,StartDate 的最小值和EndDate 的最大值。希望以下数据模型有助于解释 - 谢谢

数据:

  Category  StartDate   EndDate
  -------------------------------
       A    1/1/2018    1/11/2018
       A    1/3/2018    1/13/2018
       B    1/1/2018    1/11/2018
       B    1/9/2018    1/19/2018
       A    1/5/2018    1/15/2018
       C    1/4/2018    1/14/2018
       A    1/1/2018    1/11/2018
       C    1/7/2018    1/17/2018

想要的查询结果:

  Category  StartDate   EndDate
  --------------------------------
       A    1/1/2018    1/15/2018
       B    1/1/2018    1/19/2018
       C    1/4/2018    1/17/2018

【问题讨论】:

    标签: sql sql-server max min


    【解决方案1】:

    GROUP BYMIN()MAX() 有什么问题?

    select Category, min(startdate) startdate, max(enddate) enddate
    from table t
    group by Category;
    

    【讨论】:

      【解决方案2】:

      使用分组方式

      select category, min(startDate), max(endDate)
      from my_table  
      group by category
      

      【讨论】:

      • 谢谢!我认为它会涉及更多。
      猜你喜欢
      • 1970-01-01
      • 2015-02-03
      • 1970-01-01
      • 1970-01-01
      • 2022-11-25
      • 2018-10-20
      • 2021-12-08
      • 2018-11-26
      • 1970-01-01
      相关资源
      最近更新 更多