I’ve got a column oriented table that specifies manufacturing options for a product. Each option can be a subset of the following choices (‘ ‘, ‘B’,’L’,’R’,’BX’,’LX’,’RX). The table has 314 columns. (This is a legacy build and not the way I’d do it today…)
I have a customer request to count the number of times an option was used within a date range. Getting to the filtered data is not a problem, but getting the column oriented table converted to a countable row-oriented table is challenging my pivot/unpivot skills.
I can get the column names with this (as referenced from http://www.simple-talk.com/community/blogs/andras/archive/2007/09/14/37265.aspx)
declare @cols nvarchar(max)
select @cols = coalesce(@cols + ',' + quotename(column_name), quotename(column_name))
from information_schema.columns where table_name = 'mfgOptions'
and data_type = 'char' and character_maximum_length
Most of the time, the options have a ‘ ‘ value. I don’t want to include these in my pivoted table.
My desired result is a table like:
MfgItemID | MfgOptionName | OptionSelection
-------------------------------------------
1000 | option1 | BX
1000 | option2 | B
2000 | option1 | LX
2000 | option3 | RX
using the @cols definition above, I created the following UNPIVOT
declare @query nvarchar(max)
set @query = N'SELECT MfgItemID, MfgOptionName, OptionSelection
from (SELECT MfgItemID, ' + @cols + '
FROM mfgOptions) a
UNPIVOT (OptionSelection for MfgOptionName IN (' + @cols + ') ) AS u
order by MfgItemID, MfgOptionName'
EXECUTE(@query)
This query is executing and appears to mostly do what I need. However it takes an extremely long time as I have 500,000+ rows in the table. If I could eliminate all blank options before unpivoting, I think it would run much faster.
Does anyone have any suggestions on how to filter field values prior to unpivoting?
You can’t put a
WHEREinside theUNPIVOTclause and you can’t filter out in your subquery that returnsabecause there may be other values on the row that are useful. The best thing I know that you can do is sayWHERE u.OptionSelection <> ' 'after theUNPIVOTlike so: