Run Code
|
API
|
Code Wall
|
Misc
|
Feedback
|
Login
|
Theme
|
Privacy
|
Patreon
Row wise arithmetic operation using pivot and unpivt
Language:
Ada
Assembly
Bash
C#
C++ (gcc)
C++ (clang)
C++ (vc++)
C (gcc)
C (clang)
C (vc)
Client Side
Clojure
Common Lisp
D
Elixir
Erlang
F#
Fortran
Go
Haskell
Java
Javascript
Kotlin
Lua
MySql
Node.js
Ocaml
Octave
Objective-C
Oracle
Pascal
Perl
Php
PostgreSQL
Prolog
Python
Python 3
R
Rust
Ruby
Scala
Scheme
Sql Server
Swift
Tcl
Visual Basic
Layout:
Vertical
Horizontal
CREATE TABLE Sales (EmpId INT, Yr INT, price MONEY) INSERT Sales VALUES(1, 2005, 12000) INSERT Sales VALUES(1, 2006, 18000) INSERT Sales VALUES(1, 2007, 25000) INSERT Sales VALUES(2, 2005, 15000) INSERT Sales VALUES(2, 2006, 6000) INSERT Sales VALUES(3, 2006, 20000) INSERT Sales VALUES(3, 2007, 24000) select * from Sales select *,sum(totalsales) over() as 'Grand Total' from ( select *,sum(totalsales) over(partition by EmpId) as 'total' from (SELECT EmpId, Yr, SUM(price) as totalsales FROM Sales GROUP BY EmpId, Yr) as abc ) as def go declare @yearColumn varchar(500) declare @yearColumnCommaSeperated varchar(500) set @yearColumn = '' set @yearColumnCommaSeperated = '' select @yearColumnCommaSeperated = @yearColumn+'['+CONVERT(varchar(5), Yr)+'], ' from Sales where yr is not null set @yearColumn= STUFF((SELECT distinct ',' + QUOTENAME(yr) FROM Sales c FOR XML PATH(''), TYPE ).value('.', 'NVARCHAR(MAX)') ,1,1,'') declare @totalColumn varchar(500) set @totalColumn= STUFF((SELECT distinct '+' + QUOTENAME(yr) FROM Sales c FOR XML PATH(''), TYPE ).value('.', 'NVARCHAR(MAX)') ,1,1,'') select @yearColumn declare @query varchar(500) set @query = ' select * from ( select *,sum(totalsales) over(partition by EmpId) as total from ( SELECT EmpId, Yr, SUM(price) as totalsales FROM Sales GROUP BY EmpId, Yr ) as abc ) src pivot ( sum(totalsales) for yr in ('+@yearColumn+') ) piv order by piv.EmpID' exec(@query)
View schema
Execution time: 0.05 sec, rows selected: 30, rows affected: 7, absolute service time: 0.2 sec
fork mode
|
history
|
discussion
EmpId
Yr
price
1
1
2005
12000.0000
2
1
2006
18000.0000
3
1
2007
25000.0000
4
2
2005
15000.0000
5
2
2006
6000.0000
6
3
2006
20000.0000
7
3
2007
24000.0000
EmpId
Yr
totalsales
total
Grand Total
1
1
2005
12000.0000
55000.0000
120000.0000
2
1
2006
18000.0000
55000.0000
120000.0000
3
1
2007
25000.0000
55000.0000
120000.0000
4
2
2005
15000.0000
21000.0000
120000.0000
5
2
2006
6000.0000
21000.0000
120000.0000
6
3
2006
20000.0000
44000.0000
120000.0000
7
3
2007
24000.0000
44000.0000
120000.0000
(No column name)
1
[2005],[2006],[2007]
EmpId
total
2005
2006
2007
1
1
55000.0000
12000.0000
18000.0000
25000.0000
2
2
21000.0000
15000.0000
6000.0000
NULL
3
3
44000.0000
NULL
20000.0000
24000.0000