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