I've read many posts with similar questions, but haven't found an answer yet. I'm quite new to SQL. Using SQL Server Express 2008.
My goal is to get a single-column result of all values that are distinct among several columns with similar names. Related columns have the same base name (suffix), followed by an integer. I have many groups of columns, so I don't want to hard-code the query.
Fruit1 Coating1 Temperature1 Fruit2 Coating2 Temperature2 Fruit3 Coating3 Temperature3
-----------------------------------------------------------------------------------
apple caramel 72.5 pear chocolate 74.1 apple chocolate 98.6
pear caramel 73.3 peach chocolate 42.7 apple chocolate 33.0
So I want the server to return, for example, all the fruits used in any/all fruit columns apple peach pear
I already know how to get a list of the column names using a wildcard:
SELECT Column_name AS columnNames
FROM INFORMATION_SCHEMA.COLUMNS
WHERE Column_name LIKE 'Fruit%'
I also know how to find distinct values from columns if I already know the column names:
SELECT DISTINCT Fruit FROM(
SELECT Fruit1 as Fruit from FruitBasket
UNION
SELECT Fruit2 as Fruit from FruitBasket
UNION
SELECT Fruit3 as Fruit from FruitBasket)
AS finalOutput
What I need to know is how to use the column-name results from the first query in the UNION parameters of the second. Should I use a FOR loop or something?
Thanks!