Search code examples
sqlsql-server-2014

Trying to fuse row when with same "name"


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 :

  1. The displayed column Value1 and Value 2 both come from the same column, of the same table, and use the same dataset. The only difference is that sometime a condition is met and other time not.
  2. The table can have several fields with the same name, but we want to display only one result for each name.
  3. I cannot modify the table, or its structure in any way, shape or form, even if I think the structure could be improved a lot.

If anyone knows of a way to do this, it would help a lot.


Solution

  • 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.