So I have a table like this
Table 1
Quote Ref | Product A | Product B | Product C | Product D
-----------+-----------+-------------+-----------+-----------
12 | 222333 | 4748847478 | 0 | 0
I need to find out which Business Group this belongs to using the below Table .
I am not interested in fields for the Products that equal zero as the quote does not have those products so no Business Group to map . For this quote the Product A and B column have a non zero value and can be mapped to a business group. ( KEY POINT )
Table 2
Product Line | Business Group
Product A | Manfacturing
Product B | Tech Net
So I look to UNPIVOT data in Table 1 .
SELECT [QUOTE Ref], [Product Line], [Value]
FROM
(SELECT [QUOTE Ref], [Product A], [Product B], [Product C], [Product D]
FROM [Table1]) p
UNPIVOT
([Value] FOR [Product Line]
IN ([Product A], [Product B], [Product C], [Product D] )
)AS unpvt;
DATA for table 1 now like this
Quote Ref | Product Line | Value
-----------+--------------+------------
12 | Product A | 222333
12 | Product B | 4748847478
12 | Product C | 0
12 | Product D | 0
The problem is that 40 k rows NOW becomes 4.7 million rows .
Now I know I dont need the rows in the unpivoted table where the value for a Product Line equals zero . How can I remove these entries in the unpivot query or is there something I could do to the base table before I even start the UNPIVOT ? My database is nto big enough to cope with about 20 similar tables and 60 extra million rows in the database.
You should add the condition that removes the entries that have
value = 0in the final result set. You couldn’t do this in the SELECT query that produces the data, so enclose your current result set as subquery like this:DEMO