【问题标题】:Grouping data of one type in SQL Server在 SQL Server 中对一种类型的数据进行分组
【发布时间】:2019-03-04 17:01:59
【问题描述】:

我必须将某些类型的数据分组到视图中的一行。我不知道如何在 SQL Server 中处理这种类型的结果。

表格数据:

| Process   | StartDate | EndDate      |
+-----------+-----------+--------------+ 
| A1        | 05-06-2018|     NULL     | 
| A2        |    NULL   | 08-03-2018   | --Here A1 & A2 are same process
| B1        | 03-02-2018|     NULL     |
| C1        | 07-06-2018|     NULL     | 
| C2        |    NULL   | 09-03-2018   | --Here C1 & C2 are same process

期望的输出:

| Process   | StartDate | EndDate      |
+-----------+-----------+--------------+
| A         | 05-06-2018|  08-03-2018  | 
| B         | 03-02-2018|     NULL     | 
| C         | 07-06-2018|   09-03-2018 |

【问题讨论】:

    标签: sql sql-server database sql-server-2008 group-by


    【解决方案1】:

    你可以使用聚合:

    select left(process, 1) as process, max(startdate) as startdate), max(enddate) as enddate
    from data
    group by left(process, 1);
    

    【讨论】:

      【解决方案2】:

      看来您存储数据的方式很糟糕,它应该为serial # 提供单独的第一列,process 的其他列,但您可以这样做:

      select left(process, 1), max(startdate) as sartdate, max(enddate) as enddate
      from data d
      group by left(process, 1);
      

      根据评论,您也可以这样做:

      select dd.Process, max(startdate) as sartdate, max(enddate) as enddate
      from data d cross apply
           ( values (case when Process in ('A1','A2') then 'A'
                          when Process = 'B1' then 'B'
                          when Process in ('C1','C2') then 'C' 
                     end) 
           ) dd(Process)
      group by dd.Process;
      

      【讨论】:

        【解决方案3】:

        用例当

        select case when Process  in ('A1','A2') then 'A' 
                    when Process  in ('C1','C2') then 'C' 
                     else Process  as p,max(StartDate),max(EndDate)
         from t
        group by case when Process  in ('A1','A2') then 'A' 
                    when Process  in ('C1','C2') then 'C' 
                     else Process
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2011-01-19
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2022-11-15
          • 1970-01-01
          • 2021-02-03
          • 1970-01-01
          相关资源
          最近更新 更多