我不想要NULL并且想要在一行中包含值

时间:2020-07-23 17:11:30

标签: sql sql-server

create table employee(
    empid int,
    name varchar(5),
    salarytype varchar(10),
    salary int
)

insert into employee values (1, 'A' ,'Fixed', 500);
insert into employee values (1, 'A' ,'Variable', 300);
insert into employee values (2, 'B' ,'Fixed', 500);
insert into employee values (3, 'C' ,'Fixed', 500);`
select empid,name,  Fixed = STRING_AGG(CASE When salarytype='Fixed' then salary end,' '),
       Variable = CASE When salarytype='Variable' then salary end
From employee
group by empid,name,salarytype,salary`

在输出下面的此查询中,我得到了empid即将出现2次的位置,但我只希望它出现1次。

![1]:https://i.stack.imgur.com/voYZ7.png

所需的输出是

![2]:https://i.stack.imgur.com/420bB.png

1 个答案:

答案 0 :(得分:0)

我认为您需要修复GROUP BY和表达式:

select empid, name,
       STRING_AGG(CASE When salarytype = 'Fixed' then salary end, ' ') as fixed,
       SUM(CASE When salarytype = 'Variable' then salary end) as variable
From employee
group by empid, name
相关问题