0

I am a little bit new to SQL. So hope you can help me with this question as I didnt find answer yet. I have joined tables from other sources and I need to create new columns based on unique values of one column with summ of another col. values.

For example, this is my table:

enter image description here

And this is what I need to get (Summ of A for each unique value in B added as a column):

enter image description here

For now I can do it manually like this:

SELECT 
    EM.[id]
    ,SUM(CASE WHEN AM.[B]='ZA' THEN EM.[A] ELSE 0 END) "ZA_sum_A"
    ,SUM(CASE WHEN AM.[B]='ZB' THEN EM.[A] ELSE 0 END) "ZB_sum_A"
FROM [xxx].x.x  AS AM
  INNER JOIN [yyy].[y].[y] AS EM ON (AM.ELEMENT = EM.ELEMENT)
  WHERE ...
GROUP BY EM.[id]

But issue is that I can have hundreds of unique values in B. So, question how to do it correctly..

2
  • Your code is correct. Commented Mar 11, 2020 at 13:15
  • I know, issue that now it's hardcoded each column manually. But it could be hundreds of types in B - a little bit unhealthy manually create each column.. Commented Mar 12, 2020 at 15:19

1 Answer 1

1

If you just want to see the summed values of EM.[A] for each combination of EM.[id] and AM.[B], you can do:

select
    em.[id],
    am.[B],
    sum(em.[A])
from [xxx].x.x as am
join [yyy].[y].[y] as em on am.ELEMENT = em.ELEMENT
where [...]
group by em.[id], am.[B]

If you then want to have the distinct values of AM.[B] appear as columns, so there is only one row for each distinct value of EM.[id], you either need to know what the distinct values of AM.[B] are and use PIVOT.

If the exact values of AM.[B] are not known, or change often over time, you'll need to do something dynamic, like in this answer, but in the opposite direction.

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

1 Comment

No problem, feel free to accept the answer if you found it useful.

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.