SQL查询按类别分组

时间:2019-04-24 21:37:41

标签: sql sql-server

使用SQL Server 2016

我有下表:

Action Id   Epic    Due Date    First Name
Action 1    Epic 1  27-Feb-19   Tom
Action 2    Epic 2  28-Feb-19   John
Action 3    Epic 3  1-Mar-19    Ana
Action 4    Epic 3  15-Apr-19   Ana

是否可以使用以下输出设计查询?

Action/Epic   Due Date  First Name   Type
Epic 1                               Epic
Action 1      27-Feb-19 Tom          Action
Epic 2                               Epic
Action 2      28-Feb-19 John         Action
Epic 3                               Epic
Action 3      1-Mar-19  Ana          Action
Action 4      15-Apr-19 Ana          Action

1 个答案:

答案 0 :(得分:3)

是的,您可以用这种方式(我想这是多种方式之一):

表格

create table test (
    actionid varchar(100),
    epic varchar(100),
    duedate varchar(100),
    firstname varchar(100)
);

insert into test values
('Action 1', 'Epic 1', '27-Feb-19', 'Tom'),
('Action 2', 'Epic 2', '28-Feb-19', 'John'),
('Action 3', 'Epic 3', '1-Mar-19', 'Ana'),
('Action 4', 'Epic 3', '15-Apr-19', 'Ana');

查询

with data as (
    select 
        row_number() over(order by actionid) as sr,
        *
    from test
),
compiled as (
    select min(sr) as sr, epic as actionid, '' as epic, '' as duedate, '' as firstname, 'Epic' as type
    from data group by epic
    union all
    select *, 'Action' as type from data
)
select actionid, epic, duedate, firstname, type from compiled order by sr, actionid desc

结果

actionid    epic    duedate   firstname type
Epic 1                                  Epic
Action 1    Epic 1  27-Feb-19   Tom     Action
Epic 2                                  Epic
Action 2    Epic 2  28-Feb-19   John    Action
Epic 3                                  Epic
Action 3    Epic 3  1-Mar-19    Ana     Action
Action 4    Epic 3  15-Apr-19   Ana     Action

示例:https://rextester.com/JIN82148

说明

  • 按actionid排序后,为每一行依次赋予一个数字
  • 对于每一行,请拔出Epic。如果史诗是重复的,请获取最小序列号
  • 获取动作记录
  • 将数据组合在一起
  • 按序列号将其排序,因为某些Epic和Action将来自同一行,因此它们将具有相同的序列号
  • 对序列号进行排序后,按Epic排序,以使E在A之前出现