T-SQL: Displaying data from multiple columns into one output column using CASE and COALESCE
I have the following SQL code that runs against a Change Request database. Each record has several columns that represent affected US regions. If the change affects a region the value will be 1 otherwise NULL.
So I am adding the values in each column to determine if more than one region is affected, the answer will be greater than 1.
I need help in how to make a change to my COALESCE and/or CASE statements to list all affected areas that have a value of 1, in the "Affected_Area" output.
Affected Regions Last Seven Days
SELECT ID,
(ISNULL(southeast,0) + ISNULL(allregions,0) + ISNULL(midamerica,0) + ISNULL(northcentral,0) + ISNULL(northeast,0) + ISNULL(pacificnorthwest,0) + ISNULL(pacificsouthwest,0)),
Affected_Area =开发者_开发百科 COALESCE(
CASE WHEN [allregions]=1 THEN 'All Regions' ELSE NULL END,
CASE WHEN [midamerica]=1 THEN 'Mid-America' ELSE NULL END,
CASE WHEN [northcentral]=1 THEN 'North Central' ELSE NULL END,
CASE WHEN [northeast]=1 THEN 'Northeast' ELSE NULL END,
CASE WHEN [pacificnorthwest]=1 THEN 'Pacific Northwest' ELSE NULL END,
CASE WHEN [pacificsouthwest]=1 THEN 'Pacific Southwest' ELSE NULL END,
CASE WHEN [southeast]=1 THEN 'Southeast' ELSE NULL END
),
FROM [DB_Reporting].[dbo].change c with (nolock)
WHERE convert(varchar(10),([needed_by_date]),110) BETWEEN (DATEADD(DD,-7,CONVERT(VARCHAR(10),GetDATE(),110))) AND (DATEADD(DD,-1,CONVERT(VARCHAR(10),GetDATE(),110)))
Any help is appreciated!
Hank Stallings
Try something like this:
SELECT ID,
(ISNULL(southeast,0) + ISNULL(allregions,0) + ISNULL(midamerica,0) + ISNULL(northcentral,0) + ISNULL(northeast,0) + ISNULL(pacificnorthwest,0) + ISNULL(pacificsouthwest,0)),
Affected_Area =
CASE WHEN [allregions]=1 THEN 'All Regions, ' ELSE '' END +
CASE WHEN [midamerica]=1 THEN 'Mid-America, ' ELSE '' END +
CASE WHEN [northcentral]=1 THEN 'North Central, ' ELSE '' END +
CASE WHEN [northeast]=1 THEN 'Northeast, ' ELSE '' END +
CASE WHEN [pacificnorthwest]=1 THEN 'Pacific Northwest, ' ELSE '' END +
CASE WHEN [pacificsouthwest]=1 THEN 'Pacific Southwest, ' ELSE '' END +
CASE WHEN [southeast]=1 THEN 'Southeast' ELSE '' END
FROM [DB_Reporting].[dbo].change c with (nolock)
WHERE convert(varchar(10),([needed_by_date]),110) BETWEEN (DATEADD(DD,-7,CONVERT(VARCHAR(10),GetDATE(),110))) AND (DATEADD(DD,-1,CONVERT(VARCHAR(10),GetDATE(),110)))
You'll likely need to trim a trailing comma.
Do you have any ability to change the design of this table? It seems less than correct - you'd be better with a region column with an FK off to a regions table. What will you do with the above if you have to add another region...
If you don't, you might want to use the PIVOT command and create a more normalised view that you can then use to query.
精彩评论