You can use CROSS APPLY
:
SELECT x.raw_item_nos
FROM jtjobfil_sql t
CROSS APPLY
(
VALUES
(t.raw_item_no),
(t.raw_item_no_2),
(t.raw_item_no_3),
(t.raw_item_no_4)
) X (raw_item_nos)
WHERE job_no = 213418;
Question
I have this query
select
raw_item_no,
raw_item_no_2,
raw_item_no_3,
raw_item_no_4
from jtjobfil_sql
where job_no = 213418
which outputs like this
raw_item_no raw_item_no_2 raw_item_no_3 raw_item_no_4
23 24 25 26
how do I get the output to look like this
raw_item_nos
23
24
25
26
I looked into pivot but I couldn't figure out how to do this because I am not summing any columns.
Solution
You can use CROSS APPLY
:
SELECT x.raw_item_nos
FROM jtjobfil_sql t
CROSS APPLY
(
VALUES
(t.raw_item_no),
(t.raw_item_no_2),
(t.raw_item_no_3),
(t.raw_item_no_4)
) X (raw_item_nos)
WHERE job_no = 213418;
OTHER TIPS
In your case all you need UNPIVOT
and list of columns.
Query is very simple
SELECT P AS raw_item_no
FROM (
SELECT raw_item_no
,raw_item_no_2
,raw_item_no_3
,raw_item_no_4
FROM jtjobfil_sql
WHERE job_no = 213418
) p UNPIVOT ( p FOR value IN ( raw_item_no, raw_item_no_2, raw_item_no_3, raw_item_no_4 ) ) AS unvpt
here is sample data and example of UNPIVOT
DECLARE @table TABLE
(
raw_item_no INT
,raw_item_no_2 INT
,raw_item_no_3 INT
,raw_item_no_4 INT
)
INSERT INTO @table
VALUES ( 23, 24, 25, 26 )
SELECT P AS raw_item_no
FROM (
SELECT raw_item_no
,raw_item_no_2
,raw_item_no_3
,raw_item_no_4
FROM @table
) p UNPIVOT ( p FOR value IN ( raw_item_no, raw_item_no_2, raw_item_no_3, raw_item_no_4 ) ) AS unvpt
You could do something using a union.
with my_query (column1, column2, column3)
as
(
SELECT column1, column2, column3
FROM my_table
where id = 1
)
SELECT column1 FROM my_query
UNION
SELECT column2 FROM my_query
UNION
SELECT column3 FROM my_query
You can use this trick also to solve the particular name only
this is also one type of logic to handle this type of Question but this is very more lengthy code
SELECT substr(ename,1,1) FROM employees WHERE ENAME='JAMES'
UNION ALL
select substr(ename,2,1) from employees WHERE ENAME= 'JAMES'
UNION ALL
select substr(ename,3,1) from employees WHERE ENAME= 'JAMES'
UNION ALL
select substr(ename,4,1) from employees WHERE ENAME= 'JAMES'
UNION ALL
select substr(ename,5,1) from employees WHERE ENAME= 'JAMES'