I’m trying to find the sum of specific values within a table, using SQL. A sample table is:
+-------+-------+-------+-------+-------+-------+-------+
| ID | Co1 | Va1 | Co2 | Va2 | Co3 | Va3 |
+-------+-------+-------+-------+-------+-------+-------+
| 01 | AA1 | 23.0| AA2 | 11.2| AA3 | 328.34|
| 02 | AA2 | 27.0| AA3 | 234.56| AA4 | 23.8|
| 03 | AA1 | 409.01| AA4 | 234.98| NULL | NULL |
+-------+-------+-------+-------+-------+-------+-------+
I have 35 such ‘Code’ columns and values.
What I need is selecting a table having only one code. Say I need Code AA3, this would be (the Code column is not required here, but only to show where I got the values):
+-------+-------+--------+
| ID | Code | Value |
+-------+-------+--------+
| 01 | AA3 | 328.34|
| 02 | AA3 | 234.56|
| 03 | AA3 | 0|
+-------+-------+--------+
And I will later need another (separate) query which contains the sum of several codes, for example the sum of codes AA1 and AA2 together.
+-------+---------+
| ID | Value |
+-------+---------+
| 01 | 34.2|
| 02 | 27.0|
| 03 | 409.01|
+-------+---------+
I was thinking about having a ‘WHERE’ and run on every 35 columns, but that would really be tedious and this does not seem too efficient. I was wondering if there was a way to do that through SQL (I can do it with Excel with an if statement and it works wonders).
Maybe if there was a way to ‘search’ through a row, return the column name and then use that column name to retrieve the number?
Let me know if you require more information =)
What you should do is store your data in a normalised form.
However…
will return the results you seek