I'm creating a list from unrelated data using UNION ALL
in order to be saved to Excel in SQL Server 2008. Only one of the SELECT
statements will have an ORDER BY
and that is where my issue arises with the following error message
'The multi-part identifier "p.Category" could not be bound.'
This is a simplified working code example that I prefer to the second one below but breaks when uncommenting the first SELECT
query:
CREATE TABLE #People(Category varchar(50), [Name] varchar(50));
INSERT INTO #People VALUES(1, 'Steve');
INSERT INTO #People VALUES(99, 'Anna');
INSERT INTO #People VALUES(2, 'Sarah');
-- Unrelated data SELECT query
--SELECT 'Best Employee' AS Matrix
-- , 'Alan' AS [Name]
--UNION ALL
SELECT CASE
WHEN p.Category = 1
THEN 'Very Active'
WHEN p.Category = 2
THEN 'Active '
ELSE 'Departed'
END AS Matrix
, p.name AS [Name]
FROM #People p
ORDER BY p.Category;
DROP TABLE #People;
After some research I found that I could rewrite the query in the following way, which would give me the desired result in this small example but not something that I would consider ideal in my real case. Is there a way to give me the correct result without resorting to sub queries like in the working example below?
CREATE TABLE #People(Category varchar(50), [Name] varchar(50));
INSERT INTO #People VALUES(1, 'Steve');
INSERT INTO #People VALUES(99, 'Anna');
INSERT INTO #People VALUES(2, 'Sarah');
SELECT *
FROM
(
-- Unrelated data SELECT query
SELECT 'Best Employee' AS Matrix
, 'Alan' AS [Name]
, '' AS Category
UNION ALL
SELECT CASE
WHEN p.Category = 1
THEN 'Very Active'
WHEN p.Category = 2
THEN 'Active '
ELSE 'Departed'
END Matrix
, p.name AS [Name]
, p.Category Category
FROM #People p
) x
ORDER BY x.Category;
DROP TABLE #People;