0

Beginner question to SQLite.

I have a table like:

CREATE TABLE raw (ID int, t int, VarID Int,  val float)
INSERT INTO raw VALUES (1, 77 , 1,177)
INSERT INTO raw VALUES (2, 77 , 2,277)
INSERT INTO raw VALUES (3, 12 , 1,112)
INSERT INTO raw VALUES (4, 12 , 2,212)
INSERT INTO raw VALUES (5, 55 , 2,255)

Here tis a timestamp, VarID indicates the to which variable the subsequent val belongs.

Now I want to get an view in which all variables are in separate columns, like:

t   var1   var2
77  177    277
12  112    212
55  None    255

For reference only:

This is the reverse question to Reorganising Data in SQLLIte)

Some code I've tried w/o getting the desired result

CREATE VIEW  view1 
AS SELECT 
t,
(SELECT val FROM raw WHERE VarID=1) as var1,
(SELECT val FROM raw WHERE VarID=2) as var2
FROM raw as r;
Community
  • 1
  • 1
BerndGit
  • 1,530
  • 3
  • 18
  • 47
  • Have you tried any code yourself to accomplish this task? – GrizzlyManBear Jan 06 '16 at 21:28
  • Yes of course: I only got to the code `CREATE VIEW view1 AS SELECT t, (SELECT val FROM r WHERE r.VarID=1) as var1, (SELECT val FROM r WHERE r.VarID=2) as var2, FROM raw as r;`which doesn't show the desired behaviour (for reason i understand). – BerndGit Jan 06 '16 at 21:29
  • Could you please include the code from your comment, formatted in your question? – GrizzlyManBear Jan 06 '16 at 21:31
  • done. incl. small adaptations form comment code, to make it executables – BerndGit Jan 06 '16 at 21:36
  • I think you can group by t and then transposing the table [this question might be usful](http://stackoverflow.com/questions/15297809/sql-transpose-full-table) – Avi Gurfinkel Jan 06 '16 at 21:38
  • Thanks for the hint 'grouping'. I found a feasible solution as shown below. – BerndGit Jan 06 '16 at 21:54

1 Answers1

0

With the hint of Avi Gurfinkel (grouping) I came up with the following solution. Is this the best way or are there more elegant ways to do this?

CREATE VIEW view1 
AS SELECT 
t,
(SELECT  val FROM raw WHERE (varID=1 and r.t=raw.t)) as var1,
(SELECT  val FROM raw WHERE (varID=2 and r.t=raw.t)) as var2
FROM raw as r
GROUP BY t;
BerndGit
  • 1,530
  • 3
  • 18
  • 47
  • The GROUP BY clauses in the subqueries are superfluous (if the combination `varID`/`t` is unique). – CL. Jan 07 '16 at 09:30