Run Code
|
API
|
Code Wall
|
Users
|
Misc
|
Feedback
|
Login
|
Theme
|
Privacy
|
Blog
MySQL - Rows to Columns
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
#MySQL 5.7.12 #please drop objects you've created at the end of the script #or check for their existance before creating #'\\' is a delimiter CREATE TABLE if not exists history (hostid INT, itemname VARCHAR(5), itemvalue INT); INSERT INTO history VALUES(1,'A',10),(1,'B',3),(2,'A',9),(2,'C',40),(2,'D',5),(3,'A',14),(3,'B',67),(3,'D',8); SELECT distinct itemname as column_name_table_header FROM history order by 1; SELECT hostid ,(case when itemname = (select distinct itemname from history a order by 1 limit 0,1) then itemvalue else '' end) as a ,(case when itemname = (select distinct itemname from history a order by 1 limit 1,1) then itemvalue else '' end) as b ,(case when itemname = (select distinct itemname from history a order by 1 limit 2,1) then itemvalue else '' end) as c ,(case when itemname = (select distinct itemname from history a order by 1 limit 3,1) then itemvalue else '' end) as d FROM history order by 1; SELECT hostid ,sum(case when itemname = (select distinct itemname from history a order by 1 limit 0,1) then itemvalue else 0 end) as a ,sum(case when itemname = (select distinct itemname from history a order by 1 limit 1,1) then itemvalue else 0 end) as b ,sum(case when itemname = (select distinct itemname from history a order by 1 limit 2,1) then itemvalue else 0 end) as c ,sum(case when itemname = (select distinct itemname from history a order by 1 limit 3,1) then itemvalue else 0 end) as d FROM history group by hostid order by 1; SELECT hostid ,sum(case when itemname = (select distinct itemname from history a order by 1 limit 0,1) then itemvalue end) as a ,sum(case when itemname = (select distinct itemname from history a order by 1 limit 1,1) then itemvalue end) as b ,sum(case when itemname = (select distinct itemname from history a order by 1 limit 2,1) then itemvalue end) as c ,sum(case when itemname = (select distinct itemname from history a order by 1 limit 3,1) then itemvalue end) as d FROM history group by hostid order by 1; drop table history;
absolute service time: 0,33 sec
edit mode
|
history
columns_name_table_header
1
A
2
B
3
C
4
D
hostid
a
b
c
d
1
1
10
2
1
3
3
2
9
4
2
40
5
2
5
6
3
14
7
3
67
8
3
8
hostid
a
b
c
d
1
1
10
3
0
0
2
2
9
0
40
5
3
3
14
67
0
8
hostid
a
b
c
d
1
1
10
3
NULL
NULL
2
2
9
NULL
40
5
3
3
14
67
NULL
8