使用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
答案 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
说明