简体   繁体   English

SQL Query按类别分组

[英]SQL Query to group by category

Using SQL Server 2016 使用SQL Server 2016

I have the following table: 我有下表:

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

Is it possible to design a query with the following output? 是否可以使用以下输出设计查询?

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

Yeah, you can do it this way (one of the many ways, I suppose): 是的,你可以这样做(我猜想有很多方法之一):

Table

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');

Query 询问

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

Result 结果

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

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

Explanation 说明

  • Give each row a number sequentially after sorting by actionid 按actionid排序后,每行按顺序给出一个数字
  • For each row, pull out the Epic. 对于每一行,拉出史诗。 If epic is duplicate, get the minimum serial number 如果史诗重复,请获取最小序列号
  • Get the action records 获取行动记录
  • Combine the data together 将数据组合在一起
  • Sort it by the serial number knowing that some Epic and Action will have the same serial number since they originated from the same row 通过序列号对其进行排序,因为知道某些Epic和Action将具有相同的序列号,因为它们来自同一行
  • After serial number is sorted, sort by Epic so that E comes before A 序列号排序后,按Epic排序,以便E出现在A之前

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM