sql - Convert rows to columns with pivoting -
i learning sql , want make query makes new columns made of values table. have column named transactions , there multiple transactions same company. table looks this:
id name payd 1 john 5.00 2 adam 5.00 3 john 10.00 4 john 10.00 5 adam 15.00 i want make this:
id name 5.00 10.00 15.00 sum 1 john 5.00 20.00 0 25.00 2 adam 5.00 0 15.00 20.00 i considering doing pivot function i'm having trouble implementation. code looks this:
(select emplployer, cast (4.00 decimal(10,0)) [4.00], cast (5.00 decimal(10,0)) [5.00], cast (10.00 decimal(10,0)) [10.00], cast (18.00 decimal(10,0)) [18.00], cast (20.00 decimal(10,0)) [20.00] (select name, cast(payd decimal(10,0)) summ employee) q1 pivot ( sum(summ) employer in ([4.00], [5.00], [10.00], [18.00], [20.00]) )pvt;
conditional aggregation method:
select name ,sum(case when payd = 5 payd else 0 end) [5.00] ,sum(case when payd = 10 payd else 0 end) [10.00] ,sum(case when payd = 15 payd else 0 end) [15.00] ,sum(payd) [sum] @employees group name one way using pivot:
;with cte ( select name ,payd ,payd paydcolnames @employees ) select name ,[5.00] = isnull([5.00],0) ,[10.00] = isnull([10.00],0) ,[15.00] = isnull([15.00],0) ,[sum] = isnull([5.00],0) + isnull([10.00],0) + isnull([15.00],0) cte pivot ( sum(payd) paydcolnames in ([5.00],[10.00],[15.00]) ) p the problem appear having attempting use same column pivot on aggregate doesn't give desired result. have replicate payd column can use data both pivot , aggregate. because desire 0 when value null have use isnull or coalesce eliminate null. in opinion conditional aggregation serve better use this.
test data
declare @employees table (id int, name varchar(50), payd money) insert @employees values (1,'john',5.00) ,(2,'adam',5.00) ,(3,'john',10.00) ,(4,'john',10.00) ,(5,'adam',15.00)
Comments
Post a Comment