0

I have an SQL table like the following:

---------------------------
| Timestamp | Value | Name|
---------------------------
| 12345678  | 2     | abc |
---------------------------
| 12345678  | 3     | abc |
---------------------------
| 78910111  | 4     | cde |
--------------------------
| 56789101  | 1     | abc |
---------------------------
| 56789101  | 2     | cde |
---------------------------

I need to transform it into something like this:

-------------------------
| Timestamp | abc | cde |
-------------------------
| 12345678  |  5  |  0  |
-------------------------
| 56789101  |  1  |  2  |
-------------------------
| 78910111  |  0  |  4  |
-------------------------

Where values in the above table are sums for a particular Name at a particular timestamp the names in the lower table are not known and can be dynamic. I need a SQL query to do this.

5
  • Found a related article, that provides some answers: stackoverflow.com/questions/1599788/… Commented Jun 6, 2014 at 7:48
  • 1
    what if you have 1000+ Name in the table ? Commented Jun 6, 2014 at 7:53
  • While there is an upper limit of column rows that needs to be watched. If that is not really an issue (you are going to have comfortably less than 1000 columns) and you want to do this dynamically then you need to be looking at Dynamic SQL (for SQL Server) PL/SQL (for Oracle), etc. What system are you using? Commented Jun 6, 2014 at 8:44
  • possible duplicate of Transpose rows into columns in MySQL Commented Jun 6, 2014 at 9:33
  • 1
    Who upvotes this stuff? Commented Jun 6, 2014 at 9:33

1 Answer 1

0

You can Try following query:-

SELECT timestamp, SUM(CASE WHEN name = 'abc' THEN VALUE ELSE 0 END) AS abc,
SUM(CASE WHEN name = 'cde' THEN VALUE ELSE 0 END) AS cde
FROM tab
GROUP BY timestamp;

Here is the SQL Fiddle.

http://sqlfiddle.com/#!2/a721f4/8

Sign up to request clarification or add additional context in comments.

1 Comment

The Names are not known before hand and can be more more than 2.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.