Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding row with null field to another row

I have a table in my SQL Server database that looks like:

Date  Hours  Name
11-01    3      a
11-01    4      b
11-01    6      null
12-01    2      a
12-01    3      c
12-01    1      null

I want to add the hours from the "null" column into the "a" column for each month. So it would look like: Date  Hours  Name
11-01    9      a
11-01    4      b
12-01    3      a
12-01    3      c

The only way I was able to get this to work was by modifying the table prior to the select to prevent the null from showing up. But I'd like to be able to do this without modifying the database.

What would be the best way to go about this?

Thanks

like image 588
user1884034 Avatar asked Oct 22 '22 23:10

user1884034


1 Answers

This'll do it for you - grouping by name or 'a' (when name is null) conditionally, and taking the sum of hours from there.

SELECT Date, SUM(Hours) AS Hours, MAX(Name) AS Name
FROM TableName
GROUP BY (CASE WHEN Name IS NULL THEN 'a' ELSE Name END)
like image 88
Steven Moseley Avatar answered Oct 27 '22 10:10

Steven Moseley