Alternating Results of two SQL queries - sql

This is probably not possible, but is there a way to output the results of two queries in alternating lines on a table?
For example if I have two tables that are trying to show one widget vs all of the widgets in its category, I would output each widget followed by the category averages, followed by widget 2 with its category averages in the next line. This would result in 4 lines. This is all assuming that widgets and their category averages are in two separate tables.
Sorry if this was confusing, I can clarify if I need to. I'm just trying to make it very simple for the final application to display in C#. It would probably be easier to do in the actual application but I'm not very familiar with C#...

First - as said in the comments - If you have a field to order by you can use one select with union and order by. and you are done.
Even if not (different ordering on each query) it's stil possible (assuming the two queries have the same exact schema):
SELECT *
FROM (SELECT ROW_NUMBER() OVER (ORDER BY ColA) OrderA,1 OrderB,*
FROM A
UNION ALL
SELECT ROW_NUMBER() OVER (ORDER BY ColB) + 1 OrderA,2 OrderB, *
FROM B) C
ORDER BY OrderA, OrderB
Disclaimer - I don't think it's a database operation.

This is possible using two table variables, two sort columns in each and a union all, but I would recommend that you join the two tables together and have one row for each widget (can have many columns one for category averages) and manage the display aspects of the design on the C# side

If you have two temporary tables with identity columns, you can select a UNION of both tables with a careful manipulation of the row number:
declare #linesA table
(
lineid int identity(1,1) primary key clustered,
line varchar(80)
)
declare #linesB table
(
lineid int identity(1,1) primary key clustered,
line varchar(80)
)
insert into #linesA (line)
select 'A - 1'
union select 'A - 2'
union select 'A - 3'
insert into #linesB (line)
select 'B - 1'
union select 'B - 2'
union select 'B - 3'
select
lineid * 2 as RowNum,
line from #linesA
union select
lineid * 2 + 1 as RowNum,
line from #linesB
order by RowNum
If you don't have an identity column, then create one with ROW_NUMBER() like this:
select
row_number() over (order by line) * 2 as RowNum,
line from #linesA
union select
(row_number() over (order by line) * 2) + 1 as RowNum,
line from #linesB
order by RowNum

as updated in the comments.
first CTE is to generate only ODD and Even Numbers
remember that by default max allowed recursion is 100.
so we are setting value of #I to the number of records in to first table.
also notice the "OPTION (MAXRECURSION 0);" which is required if number of records happen to be more that 100 and in that case recursion happen that many times.
DECLARE #widget TABLE
(
widgetID INT
,widgetName sysname
,WidgetType sysname
)
DECLARE #categoryAvg TABLE
(
WidgetType sysname
,categoryAvg sysname
)
INSERT INTO #widget( widgetID, widgetName,WidgetType )
SELECT 1,'widget1','Wtype1'
UNION ALL SELECT 2,'widget2','Wtype1'
UNION ALL SELECT 2,'widget3','Wtype2'
UNION ALL SELECT 2,'widget4','Wtype2'
INSERT INTO #categoryAvg( WidgetType, categoryAvg )
SELECT 'Wtype1',10 UNION ALL SELECT 'Wtype2',20
declare #i int=100--MAX 100 ByDefault
declare #StartOdd int=1 --To generate ODD numbers
declare #StartEven int=2 --To generate EVEN numbers
SELECT #i = COUNT(*) From #widget
;WITH CTE_OE(Rowid,OddNum,EvenNum)
as
(
select 1,#StartOdd,#StartEven
union all
select t1.rowid+1,t1.OddNum+2,t1.EvenNum+2
from CTE_OE t1
where t1.rowid<#i
),
CTE_1(WidgetType,OutputColumn,RowID)
AS
(
SELECT t1.WidgetType,t1.OutputColumn,t2.OddNum
FROM
(
SELECT WidgetType
,widgetName As OutputColumn
,ROW_NUMBER() OVER (ORDER BY widgetName,WidgetType) RowID
FROM #widget
)t1
JOIN CTE_OE t2
ON t1.RowID=t2.Rowid
),
CTE_2(OutputColumn,RowID)
AS
(
Select t1.OutputColumn
,t2.EvenNum
From
(
SELECT 'Type'+ ' = ' + q1.WidgetType + ', Avg = ' + q1.categoryAvg As OutputColumn
,ROW_NUMBER() OVER (ORDER BY q1.WidgetType) AS RowID
FROM #categoryAvg q1
JOIN CTE_1 q2
on q1.WidgetType=q2.WidgetType
)t1
JOIN CTE_OE t2
ON t1.RowID=t2.Rowid
)
Select OutputColumn
From
(
Select OutputColumn,RowID from CTE_1
union all
select OutputColumn,RowID from CTE_2
)qry
order by RowID
OPTION (MAXRECURSION 0);

I don't know C# personally, so I don't know how hard/easy this would be to do within the application, but just as a side thought, one way you might be able to approach it within the SQL query without having to make the two separate queries and alternate display and all... an option might be to just do a join and display results side by side. What I mean is you could do something along the lines of:
SELECT Widget.Name, Widget.Category, Widget.Speed, Category.Speed AS AvgSpeed
FROM Widget
INNER JOIN Category
ON Widget.Category=Category.Name;
Then you would end up having a table something along the lines of
Name Category Speed AvgSpeed
W1 Sample 1ms 2ms

Related

How to ROWCOUNT_BIG() value with union all

I have the following query in SQL Server. How do I get the number of rows of previous select query as following format?
Sample Query
select ID, Name FROM Branch
UNION ALL
SELECT ROWCOUNT_BIG(), ''
Sample Output
If you use a CTE you can count the rows and union all together:
with cte as (
select ID, [Name]
from dbo.Branch
)
select ID, [Name]
from cte
union all
select count(*) + 1, ''
from cte;
I think you want to see total count of the select statement. you can do this way.
CREATE TABLE #test (id int)
insert into #test(id)
SELECT 1
SELECT id from #test
union all
SELECT rowcount_big()
Note: Here, the ID will be implicitly converted to BIGINT datatype, based on the datatype precedence. Read more
Presumably, you are running this in some sort of application. So why not use ##ROWCOUNT?
select id, name
from . . .;
select ##rowcount_big; -- big if you want a bigint
I don't see value to including the value in the same query. However, if the underlying query is an aggregation query, there might be a way to do this using GROUPING SETS.
Here are two ways. It's better to use a CTE to define the row set so further table inserts don't interfere with the count. Since you're using ROWCOUNT_BIG() these queries use COUNT_BIG() (which also returns bigint) to count the inserted rows. In order to make sure the total always appears as the last row an 'order_num' column was added to the SELECT list and ORDER BY clause.
drop table if exists #tTest;
go
create table #tTest(
ID int not null,
[Name] varchar(10) not null);
insert into #tTest values
(115, 'Joe'),
(116, 'Jon'),
(117, 'Ron');
/* better to use a CTE to define the row set */
with t_cte as (
select *
from #tTest)
select 1 as order_num, ID, [Name]
from t_cte
union all
select 2 as order_num, count_big(*), ''
from t_cte
order by order_num, ID;
/* 2 separate queries could give inconsistent result if table is inserted into */
select 1 as order_num, ID, [Name]
from #tTest
union all
select 2 as order_num, count_big(*), ''
from #tTest
order by order_num, ID;
Both return
order_num ID Name
1 115 Joe
1 116 Jon
1 117 Ron
2 3

Msg 120, Level 15, State 1, Procedure Generate_Exame, Line 6,The select list for the INSERT statement contains fewer items than the insert list

I want insert in question table that has these columns
C#_T_F_Id, C#_T_F_Q, C#_T_F_Choices, C#_Mcq_Id, C#_MCQ_Q, C#_Choices
After execute Generate_Exame procedure what should I do :
create procedure Generate_Exame
#course_id int
as
if #course_id = 600
begin
insert into [dbo].[Question](C#_T_F_Id, C#_T_F_Q, C#_T_F_Choices,
C#_Mcq_Id, C#_MCQ_Q, C#_Choices)
select *
from
(select top(3)
T.C#_T_F_Id, T.C#_T_F_Q, T.C#_T_F_Choices
from
C#_T_F T
order by
newid()) as t1
union all
select *
from
(select top(7)
C.C#_Mcq_Id C#_Q_id, C.C#_MCQ_Q C#_question, C.C#_Choices Choices
from
C#_MCQ C
order by
newid()) as t2)
end
If I understand well you want to:
Insert data into a table from a combined result set.
Combine two result sets side by side. The first one provides columns 1, 2, and 3, while the second one provides column 4, 5, and 6.
On top of this both result sets (left and right) do not have the same lenght. One has 3 rows, while the other has 7 rows. I assume these numbers may vary.
There's no set order for the rows on the left, or the rows on the right. You are producing them by ordering using a random UUID, so that can change every time you run the query.
In order to do this you need to produce a row number on each side. Then a simple full join will combine both result sets.
For example:
insert into [dbo].[Question] (
C#_T_F_Id, C#_T_F_Q, C#_T_F_Choices,
C#_Mcq_Id, C#_MCQ_Q, C#_Choices
)
select -- Step #4: produce combined rows, ready for insert
a.T.C#_T_F_Id, a.T.C#_T_F_Q, a.T.C#_T_F_Choices,
b.C#_Q_id, b.C#_question, b.Choices
from ( -- Step #1: Produce the left result set with row number (rn)
select *, row_number() over(order by ord) as rn
from (
select top(3)
T.C#_T_F_Id, T.C#_T_F_Q, T.C#_T_F_Choices,
newid() as ord
from C#_T_F T
order by ord
) x
) a
full join ( -- Step #2: Produce the right result set with row number (rn)
select *, row_number() over(order by ord) as rn
from (
select top(7)
C.C#_Mcq_Id C#_Q_id, C.C#_MCQ_Q C#_question, C.C#_Choices Choices,
newid() as ord
from C#_MCQ C
order by ord
) y
) b on a.rn = b.rn -- Step #3: Full join both result sets by row number (rn)
You are having six columns in the INSERT clause. But, you have only 3 columns coming out of the UNION query.
-- You are inserting 6 columns
insert into [dbo].[Question](C#_T_F_Id, C#_T_F_Q, C#_T_F_Choices,
C#_Mcq_Id, C#_MCQ_Q, C#_Choices)
-- You are selecting only 3 columns.
select *
from
(select top(3)
T.C#_T_F_Id, T.C#_T_F_Q, T.C#_T_F_Choices
from
C#_T_F T
order by
newid()) as t1
union all
select *
from
(select top(7)
C.C#_Mcq_Id C#_Q_id, C.C#_MCQ_Q C#_question, C.C#_Choices Choices
from
C#_MCQ C
order by
newid()) as t2)
If you need to have 6 columns, you need to join the two SELECT statements in some way, based on JOIN condition.

SQL Using TOP n with UNION, but only want results of second query if first does not have enough records

I am trying to write a sql statement that works something like a store. I have two queries and I want n records from the first query, but if there is less than n, I want the rest from the second.
I tried using TOP n and UNION
SELECT TOP 20 FROM (
(SELECT * FROM t1)
UNION
(SELECT * FROM t2))
but the results are from both tables regardless of how many are in t1. Basically, I want the first query to have precedence. If 5 records exist there and I want them and I want the rest from t2.
Add a column that identifies the query, so the first one have precedence.
SELECT TOP 20 *
FROM ((SELECT 1 as query, * FROM t1)
UNION
(SELECT 2 as query, * FROM t2))
ORDER BY query
you can use a CTE to place a sort order on the two tables and then use that in an order by clause
declare #foo1 table(
bar INT
)
insert into #foo1
values (1),(2),(3),(4),(5),(6),(7),(8),(9),(10)
--,(11),(12),(13),(14),(15),(16),(17),(18),(19),(20)
declare #foo2 table(
bar INT
)
insert into #foo2
values (101),(102),(103),(104),(105),(106),(107),(108),(109),(110),(111),(112),(113),(114),(115),(116),(117),(118),(119),(120)
;with base_data as (
select
0 as sort,
f1.bar
FROM #foo1 f1
UNION
SELECT
1 as sort,
f2.bar
FROM #foo2 f2
)
select top 20 bar
from base_data
order by sort, bar

How to join two tables with the same number of rows in SQLite?

I have almost the same problem as described in this question. I have two tables with the same number of rows, and I would like to join them together one by one.
The tables are ordered, and I would like to keep this order after the join, if it is possible.
There is a rowid based solution for MSSql, but in SQLite rowid can not be used if the table is coming from a WITH statement (or RECURSIVE WITH).
It is guaranteed that the two tables have the exact same number of rows, but this number is not known beforehand. It is also important to note, that the same element may occur more than twice. The results are ordered, but none of the columns are unique.
Example code:
WITH
table_a (n) AS (
SELECT 2
UNION ALL
SELECT 4
UNION ALL
SELECT 5
),
table_b (s) AS (
SELECT 'valuex'
UNION ALL
SELECT 'valuey'
UNION ALL
SELECT 'valuez'
)
SELECT table_a.n, table_b.s
FROM table_a
LEFT JOIN table_b ON ( table_a.rowid = table_b.rowid )
The result I would like to achieve is:
(2, 'valuex'),
(4, 'valuey'),
(5, 'valuez')
SQLFiddle: http://sqlfiddle.com/#!5/9eecb7/6888
This is quite complicated in SQLite -- because you are allowing duplicates. But you can do it. Here is the idea:
Summarize the table by the values.
For each value, get the count and offset from the beginning of the values.
Then use a join to associate the values and figure out the overlap.
Finally use a recursive CTE to extract the values that you want.
The following code assumes that n and s are ordered -- as you specify in your question. However, it would work (with small modifications) if another column specified the ordering.
You will notice that I have included duplicates in the sample data:
WITH table_a (n) AS (
SELECT 2 UNION ALL
SELECT 4 UNION ALL
SELECT 4 UNION ALL
SELECT 4 UNION ALL
SELECT 5
),
table_b (s) AS (
SELECT 'valuex' UNION ALL
SELECT 'valuey' UNION ALL
SELECT 'valuey' UNION ALL
SELECT 'valuez' UNION ALL
SELECT 'valuez'
),
a as (
select a.n, count(*) as a_cnt,
(select count(*) from table_a a2 where a2.n < a.n) as a_offset
from table_a a
group by a.n
),
b as (
select b.s, count(*) as b_cnt,
(select count(*) from table_b b2 where b2.s < b.s) as b_offset
from table_b b
group by b.s
),
ab as (
select a.*, b.*,
max(a.a_offset, b.b_offset) as offset,
min(a.a_offset + a.a_cnt, b.b_offset + b.b_cnt) - max(a.a_offset, b.b_offset) as cnt
from a join
b
on a.a_offset + a.a_cnt - 1 >= b.b_offset and
a.a_offset <= b.b_offset + b.b_cnt - 1
),
cte as (
select n, s, offset, cnt, 1 as ind
from ab
union all
select n, s, offset, cnt, ind + 1
from cte
where ind < cnt
)
select n, s
from cte
order by n, s;
Here is a DB Fiddle showing the results.
I should note that this would be much simpler in almost any other database, using window functions (or perhaps variables in MySQL).
Since the tables are ordered, you can add row_id values by comparing n values.
But still the best way in order to get better performance would be inserting the ID values while creating the tables.
http://sqlfiddle.com/#!5/9eecb7/7014
WITH
table_a_a (n, id) AS
(
WITH table_a (n) AS
(
SELECT 2
UNION ALL
SELECT 4
UNION ALL
SELECT 5
)
SELECT table_a.n, (select count(1) from table_a b where b.n <= table_a.n) id
FROM table_a
) ,
table_b_b (n, id) AS
(
WITH table_a (n) AS
(
SELECT 'valuex'
UNION ALL
SELECT 'valuey'
UNION ALL
SELECT 'valuez'
)
SELECT table_a.n, (select count(1) from table_a b where b.n <= table_a.n) id
FROM table_a
)
select table_a_a.n,table_b_b.n from table_a_a,table_b_b where table_a_a.ID = table_b_b.ID
or convert the input set to comma separated list and try like this:
http://sqlfiddle.com/#!5/9eecb7/7337
WITH RECURSIVE table_b( id,element, remainder ) AS (
SELECT 0,NULL AS element, 'valuex,valuey,valuz,valuz' AS remainder
UNION ALL
SELECT id+1,
CASE
WHEN INSTR( remainder, ',' )>0 THEN
SUBSTR( remainder, 0, INSTR( remainder, ',' ) )
ELSE
remainder
END AS element,
CASE
WHEN INSTR( remainder, ',' )>0 THEN
SUBSTR( remainder, INSTR( remainder, ',' )+1 )
ELSE
NULL
END AS remainder
FROM table_b
WHERE remainder IS NOT NULL
),
table_a( id,element, remainder ) AS (
SELECT 0,NULL AS element, '2,4,5,7' AS remainder
UNION ALL
SELECT id+1,
CASE
WHEN INSTR( remainder, ',' )>0 THEN
SUBSTR( remainder, 0, INSTR( remainder, ',' ) )
ELSE
remainder
END AS element,
CASE
WHEN INSTR( remainder, ',' )>0 THEN
SUBSTR( remainder, INSTR( remainder, ',' )+1 )
ELSE
NULL
END AS remainder
FROM table_a
WHERE remainder IS NOT NULL
)
SELECT table_b.element, table_a.element FROM table_b, table_a WHERE table_a.element IS NOT NULL and table_a.id = table_b.id;
SQL
SELECT a1.n, b1.s
FROM table_a a1
LEFT JOIN table_b b1
ON (SELECT COUNT(*) FROM table_a a2 WHERE a2.n <= a1.n) =
(SELECT COUNT(*) FROM table_b b2 WHERE b2.s <= b1.s)
Explanation
The query simply counts the number of rows up until the current one for each table (based on the ordering column) and joins on this value.
Demo
See SQL Fiddle demo.
Assumptions
A single column in used for the ordering in each table. (But the query could easily be modified to allow multiple ordering columns).
The ordering values in each table are unique.
The values in the ordering column aren't necessarily the same between the two tables.
It is known that table_a contains either the same or more rows than table_b. (If this isn't the case then a FULL OUTER JOIN would need to be emulated since SQLite doesn't provide one.)
No further changes to the table structure are allowed. (If they are, it would be more efficient to have pre-populated columns for the ordering).
Either way...
Use something like
WITH
v_table_a (n, rowid) AS (
SELECT 2, 1
UNION ALL
SELECT 4, 2
UNION ALL
SELECT 5, 3
),
v_table_b (s, rowid) AS (
SELECT 'valuex', 1
UNION ALL
SELECT 'valuey', 2
UNION ALL
SELECT 'valuez', 3
)
SELECT v_table_a.n, v_table_b.s
FROM v_table_a
LEFT JOIN v_table_b ON ( v_table_a.rowid = v_table_b.rowid );
for "virtual" tables (with WITH or without),
WITH RECURSIVE vr_table_a (n, rowid) AS (
VALUES (2, 1)
UNION ALL
SELECT n + 2, rowid + 1 FROM vr_table_a WHERE rowid < 3
)
, vr_table_b (s, rowid) AS (
VALUES ('I', 1)
UNION ALL
SELECT s || 'I', rowid + 1 FROM vr_table_b WHERE rowid < 3
)
SELECT vr_table_a.n, vr_table_b.s
FROM vr_table_a
LEFT JOIN vr_table_b ON ( vr_table_a.rowid = vr_table_b.rowid );
for "virtual" tables using recursive WITHs (in this example the values are others then yours, but I guess you get the point) and
CREATE TABLE p_table_a (n INT);
INSERT INTO p_table_a VALUES (2), (4), (5);
CREATE TABLE p_table_b (s VARCHAR(6));
INSERT INTO p_table_b VALUES ('valuex'), ('valuey'), ('valuez');
SELECT p_table_a.n, p_table_b.s
FROM p_table_a
LEFT JOIN p_table_b ON ( p_table_a.rowid = p_table_b.rowid );
for physical tables.
I'd be careful with the last one though. A quick test shows, that the numbers of rowid are a) reused -- when some rows are deleted and others are inserted, the inserted rows get the rowids from the old rows (i.e. rowid in SQLite isn't unique past the lifetime of a row, whereas e.g. Oracle's rowid AFAIR is) -- and b) corresponds to the order of insertion. But I don't know and didn't find a clue in the documentation, if that's guaranteed or is subject to change in other/future implementations. Or maybe it's just a mere coincidence in my test environment.
(In general physical order of rows may be subject to change (even within the same database using the same DMBS as a result of some reorganization) and is therefore no good choice to rely on. And it's not guaranteed, a query will return the result ordered by physical position in the table as well (it might use the order of some index instead or have a partial result ordered some other way influencing the output's order). Consider designing your tables using common (sort) keys in corresponding rows for ordering and to join on.)
You can create temp tables to carry CTE data row. then JOIN them by sqlite row_id column.
CREATE TEMP TABLE temp_a(n integer);
CREATE TEMP TABLE temp_b(n VARCHAR(255));
WITH table_a(n) AS (
SELECT 2 n
UNION ALL
SELECT 4
UNION ALL
SELECT 5
UNION ALL
SELECT 5
)
INSERT INTO temp_a (n) SELECT n FROM table_a;
WITH table_b (n) AS
(
SELECT 'valuex'
UNION ALL
SELECT 'valuey'
UNION ALL
SELECT 'valuez'
UNION ALL
SELECT 'valuew'
)
INSERT INTO temp_b (n) SELECT n FROM table_b;
SELECT *
FROM temp_a a
INNER JOIN temp_b b on a.rowid = b.rowid;
sqlfiddle:http://sqlfiddle.com/#!5/9eecb7/7252
It is possible to use the rowid inside a with statement but you need to select it and make it available to the query using it.
Something like this:
with tablea AS (
select id, rowid AS rid from someids),
tableb AS (
select details, rowid AS rid from somedetails)
select tablea.id, tableb.details
from
tablea
left join tableb on tablea.rid = tableb.rid;
It is however as they have already warned you a really bad idea. What if the app breaks after inserting in one table but before the other one? What if you delete an old row? If you want to join two tables you need to specify the field to do so. There are so many things that could go wrong with this design. The most similar thing to this would be an incremental id field that you would save in the table and use in your application. Even simpler, make those into one table.
Read this link for more information about the rowid: https://www.sqlite.org/lang_createtable.html#rowid
sqlfiddle: http://sqlfiddle.com/#!7/29fd8/1
It is possible to use the rowid inside a with statement but you need to select it and make it available to the query using it. Something like this:
with tablea AS (select id, rowid AS rid from someids),
tableb AS (select details, rowid AS rid from somedetails)
select tablea.id, tableb.details
from
tablea
left join tableb on tablea.rid = tableb.rid;
The problem statement indicates:
The tables are ordered
If this means that the ordering is defined by the ordering of the values in the UNION ALL statements, and if SQLite respects that ordering, then the following solution may be of interest because, apart from small tweaks to the last three lines of the sample program, it adds just two lines:
A(rid,n) AS (SELECT ROW_NUMBER() OVER ( ORDER BY 1 ) rid, n FROM table_a),
B(rid,s) AS (SELECT ROW_NUMBER() OVER ( ORDER BY 1 ) rid, s FROM table_b)
That is, table A is table_a augmented with a rowid, and similarly for table B.
Unfortunately, there is a caveat, though it might just be the result of my not having found the relevant specifications. Before delving into that, however, here is the full proposed solution:
WITH
table_a (n) AS (
SELECT 2
UNION ALL
SELECT 4
UNION ALL
SELECT 5
),
table_b (s) AS (
SELECT 'valuex'
UNION ALL
SELECT 'valuey'
UNION ALL
SELECT 'valuez'
),
A(rid,n) AS (SELECT ROW_NUMBER() OVER ( ORDER BY 1 ) rid, n FROM table_a),
B(rid,s) AS (SELECT ROW_NUMBER() OVER ( ORDER BY 1 ) rid, s FROM table_b)
SELECT A.n, B.s
FROM A LEFT JOIN B
ON ( A.rid = B.rid );
Caveat
The proposed solution has been tested against a variety of data sets using sqlite version 3.29.0, but whether or not it is, and will continue to be, "guaranteed" to work is unclear to me.
Of course, if SQLite offers no guarantees with respect to the ordering of the UNION ALL statements (that is, if the question is based on an incorrect assumption), then it would be interesting to see a well-founded reformulation.

SQL Server query for getting single value from each column into a single column

I'll start directly by explaining with an example. Suppose I have a table which has 3 columns as shown.
Now what I am trying to achieve is, I want the first values of each individual column into a single column. So it would be something like this,
I have tried a few queries here including using TOP 1 and other incorrect ways. But I am still missing something here to achieve the exact output.
Need some guidance here on how to achieve this. Thank you.
SAMPLE TABLE
SELECT * INTO #TEMP
FROM
(
SELECT 1 BATCH_ID,'AAA' ASSIGNMENTTITLE,'FILE' ASSIGNMENTTYPE
UNION ALL
SELECT 1,'AAA1','FILE'
UNION ALL
SELECT 1,'AAA','FILE'
)TAB
If you need the second row specifically you can do the below
QUERY
;WITH CTE AS
(
-- Order row according to default format
SELECT ROW_NUMBER() OVER(ORDER BY (SELECT(0))) RNO,*
FROM #TEMP
)
SELECT CAST(BATCH_ID AS VARCHAR(20)) FROM CTE WHERE RNO=2
UNION ALL
SELECT ASSIGNMENTTITLE FROM CTE WHERE RNO=2
UNION ALL
SELECT ASSIGNMENTTYPE FROM CTE WHERE RNO=2
Click here to view result
UPDATE
Since there are 3 items in each record, it can be puzzled unless and otherwise an a column is for each items in a record.
;WITH CTE AS
(
-- Order row according to default format
SELECT ROW_NUMBER() OVER(ORDER BY (SELECT(0))) RNO,*
FROM #TEMP
)
SELECT CAST(BATCH_ID AS VARCHAR(20)),RNO
FROM CTE
UNION ALL
SELECT ASSIGNMENTTITLE,RNO
FROM CTE
UNION ALL
SELECT ASSIGNMENTTYPE,RNO
FROM CTE
ORDER BY RNO
Click here to view result
You can use the concat() function to create a column consisting of all the desired values
More info here
Simply you can try this. If want specific for a row use rowid. For all columns Use unpivot
create table #temp(id int, name varchar(100), title varchar(100))
insert into #temp values(1,'aaa','file')
insert into #temp values(1,'aaas','filef')
insert into #temp values(1,'aaaww','filefs')
select * from #temp
select top 1 cast(id as varchar) title from #temp
union
select top 1 name from #temp
union
select top 1 title from #temp
drop table #temp
This might help you
select top 1 convert(varchar(10), batch_id) ASSIGNMENTTITLE from table
union all
select top 1 ASSIGNMENTTITLE from table
union all
select top 1 ASSIGNMENTTYPE from table
If this is really what you want: "I want the first values of each individual column into a single column" it would be:
select ASSIGNMENTTITLE
from (
select min(convert(varchar(10), batch_id)) ASSIGNMENTTITLE,
1 ColOrder from table
union all
select min(ASSIGNMENTTITLE),
2 ColOrder from table
union all
select min(ASSIGNMENTTYPE),
3 ColOrder from table
) as data
order by ColOrder