I have a table holding training cost data for various organisational departments (e.g. how much was spent on training).I run a query and place the results into a table variable, which I can then group in different ways as required.I need to show how much each department has spent on training, for all different currencies that exist within the first set of results, e.g.siteOrgLevelID colname regionCulture totals-------------------------------------------------------------1 Durham, IT £ GBP 152502 Essex, HR £ GBP 74523 Essex, Production $ USD 32564 Essex, Production $ USD 6982
To force the query to show all currencies for each department, I use a CROSS JOIN, then LEFT OUTER JOIN my original results to SUM the costs. This allows for effective graphing at a later stage. The problem is that when no cost data exists for a department, both the [colname] and [totals] columns show NULL values. The [siteOrgLevelID] column however still shows the correct ID value. I can understand about the costs, so I use COALESCE to produce zeros, but within my initial results table (@tmp) there is ALWAYS a department name for each [siteOrgLevelID], so I don't understand what's happening.siteOrgLevelID colname regionCulture totals-------------------------------------------------------------1 Durham, IT £ GBP 152502 NULL £ GBP NULL <-- [colname] should have a value!3 Essex, Production $ USD 32564 Essex, Production $ USD 6982
Can anyone please explain how to force the query to show the department name that corresponds to the ID value?-- first put original query into @tmp (omitted)-- then...DECLARE @Depts TABLE ( siteOrgLevelID int )INSERT INTO @Depts ( siteOrgLevelID )SELECT DISTINCT(siteOrgLevelID)FROM @tmp DECLARE @regionCultures TABLE ( regionCultureID int NOT NULL, regionCultureCode nvarchar(5) not null )INSERT INTO @regionCultures ( regionCultureID, regionCultureCode )SELECT DISTINCT (regionCultureID), regionCultureCodeFROM @tmpSELECT d.siteOrgLevelID, rc.regionCultureID, rc.regionCultureCode, t.siteName + ', ' + t.orgLevelName as colname, -- NULLs get shown here when @tmp.costAmount is null SUM(COALESCE(t.costAmount, 0)) as totalsFROM @Depts d CROSS JOIN @regionCultures rc LEFT OUTER JOIN @tmp t ON t.siteOrgLevelID = d.siteOrgLevelID AND rc.regionCultureID = t.regionCultureIDGROUP BY rc.regionCultureID, rc.regionCultureCode, d.siteOrglevelID, t.siteName, t.orgLevelNameORDER BY t.siteName + ', ' + t.orgLevelName rc.regionCultureCode
I've tried to include a screen grab to illustrate this more clearly. Apologies for my long winded explanation...!
Thank you in advance!