In SQL I am trying to get two rows to fuse when their name is the same.
Right now I have a SQL query that looks like this:
SELECT TABLE.Name, SUM(TABLE.Value) AS VALUE1, 0 AS VALUE2
FROM TABLE
WHERE TABLE.Bool = true
GROUP BY TABLE.Name
SELECT TABLE.Name, 0 AS VALUE1, SUM(TABLE.Value) AS VALUE2
FROM TABLE
WHERE TABLE.Bool = false
GROUP BY TABLE.Name
Which give me a result lookin like this :
|Name |Value1 |Value2 |
------------------------------
|Name1 |1000 |0 |
|Name2 |2000 |0 |
|Name3 |3000 |0 |
|Name |Value1 |Value2 |
------------------------------
|Name1 |0 |0001 |
|Name2 |0 |0002 |
|Name3 |0 |0003 |
Using the UNION operator would yield a result such as this:
|Name |Value1 |Value2 |
------------------------------
|Name1 |1000 |0 |
|Name2 |2000 |0 |
|Name3 |3000 |0 |
|Name1 |0 |0001 |
|Name2 |0 |0002 |
|Name3 |0 |0003 |
The result I'd like to obtain is something like this:
|Name |Value1 |Value2 |
------------------------------
|Name1 |1000 |0001 |
|Name2 |2000 |0002 |
|Name3 |3000 |0003 |
Note :
Due to the way the table is built, both selects can return a different number of rows.
A bit of precision about the construction of the table :
If anyone knows of a way to do this, it would help a lot.
You can use conditional aggregation:
SELECT TABLE.Name,
SUM(case when TABLE.Bool = true then TABLE.Value else 0 end) AS VALUE1,
SUM(case when TABLE.Bool = false then TABLE.Value else 0 end) AS VALUE2
FROM TABLE
GROUP BY TABLE.Name
VALUE1
returns the sum of Value
when the condition is met, whereas VALUE2
returns the sum of Value
for the rest of the records.