2

I am sure there must be a relatively straightforward way to do this, but it is escaping me at the moment. Suppose I have a SQL table like this:

+-----+-----+-----+-----+
|  A  |  B  |  C  |  D  |
+=====+=====+=====+=====+
|  a  |  b  |  3  | 100 |  << a,b
+-----+-----+-----+-----+
|  a  |  c  |  3  | 60  |  << a,c
+-----+-----+-----+-----+
|  a  |  b  |  4  | 50  |  << a,b
+-----+-----+-----+-----+
|  a  |  b  |  5  | 30  |  << a,b
+-----+-----+-----+-----+
|  d  |  b  |  3  | 35  |  << d,b
+-----+-----+-----+-----+
|  a  |  c  |  2  | 40  |  << a,c
+-----+-----+-----+-----+

Now, I want to know how many times each combination of values for columns A and B appear, then it can hold data column D based on grouping by column C in single row. So, in this example, I want an output something like this:

+-----+-----+-----+-----+-----+
|  A  |  B  |  C3 |  C4 |  C5 |
+=====+=====+=====+=====+=====+
|  a  |  b  | 100 | 50  | 30  | << a,b
+-----+-----+-----+-----+-----+
|  a  |  c  | 60  |  0  |  0  | << a,c
+-----+-----+-----+-----+-----+
|  d  |  b  | 35  |  0  |  0  | << d,b
+-----+-----+-----+-----+-----+

What would be the SQL to determine that? I feel like this must not be a very uncommon thing to want to do.

Thanks!

1
  • 1
    Where did the a, c ,2 ,40 go? And is there a primary key constraint on your table? Commented Feb 22, 2011 at 9:00

2 Answers 2

2

You can use:

SELECT A, B,
       sum(if(C=3, D, NULL)) as C3,
       sum(if(C=4, D, NULL)) as C4,
       sum(if(C=5, D, NULL)) as C5
  FROM yourTable
GROUP BY A, B;
Sign up to request clarification or add additional context in comments.

3 Comments

This will only work if C column has values of 3, 4 or 5 only. So, the row with 2 (or other values besides those three) at C will dissapear.
Yes, you need to add the needed columns. On the question example are only C3, C4 and C5 because of this I only use this values.
Also, the rows without this C value will not disappear, only they will show 0 on C3, C4 and C5 columns
0

You can achieve a similar result by using GROUP_CONCAT (see docs), which gives you a comma-separated list of values in column D and column C and then extract your data by program.

Comments

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.