I’m trying to find a solution for my problem using MS SQL Server:

Table 1:

Column A
Value1
Value2
Value3

For above values from column A, I’m trying to “SELECT UNION” data from different tables –
(a,b,c represents few columns with data).

Problem is that my query output looks like this:

Col Col2
a Value1
a Value2
a Value3
b Value1
b Value2
b Value3
c Value1
c Value2
c Value3

And I want it to look like this:

Col Col2
a Value1
b Value1
c Value1
a Value2
b Value2
c Value2
a Value3
b Value3
c Value3

What can I do to output rows in a certain order for each value as in above example?
Maybe there is some built in option from Transact SQL to manipulate with order like that? Can I solve it with case() function?

New contributor

Rantoryu is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.

3

SELECT 'a' AS Col, Col2
FROM Table_a
UNION ALL
SELECT 'b' AS Col, Col2
FROM Table_b
UNION ALL
SELECT 'c' AS Col, Col2
FROM Table_c
ORDER BY
  CASE Col
    WHEN 'a' THEN 1
    WHEN 'b' THEN 2
    WHEN 'c' THEN 3
  END,
  Col2;

New contributor

Gunduz Heyderov is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.