Select two columns for two different tables in SQL Server 2000 - sql-server

I have a database with two tables (Table1 and Table2). Table1 has one column ColumnA and Table2 has one column ColumnB i want to select both the columns,
looking for something like:
ColumnA in Table1:
a
b
c
ColumnA in Table2:
d
e
f
Result set should be:
a d
b e
c f
Thanks in advance..

I am pretty sure sql server 2000 supports table vars so you can try this
DECLARE #TableA TABLE(
ID INT IDENTITY(1,1),
Val VARCHAR(50)
)
INSERT INTO #TableA (Val) SELECT ColumnA FROM Table1
DECLARE #TableB TABLE(
ID INT IDENTITY(1,1),
Val VARCHAR(50)
)
INSERT INTO #TableB (Val) SELECT ColumnB FROM Table2
SELECT a.Val,
b.Val
FROM #TableA a INNER JOIN
#TableB b ON a.ID = b.ID

Since you have no relation between the two tables, this operation is not really defined. What row in table1 goes with what row in table2?
You should set up a relation.
What is it you want to achieve anyway?

I don't know the big picture but from what you've said, here's an example. There has to be some way to define which record in table 1 should match up with a record in table 2. I'm assuming they match up on the ordering when ordered by the column in each table (e.g. record 1 from Table 1 ordered by column A, matches with record 1 from Table 2 ordered by column B). This example requires SQL 2005 or higher.
DECLARE #T1 TABLE (A varchar(10))
DECLARE #T2 TABLE (B varchar(10))
INSERT #T1 VALUES ('a')
INSERT #T1 VALUES ('b')
INSERT #T1 VALUES ('c')
INSERT #T2 VALUES ('d')
INSERT #T2 VALUES ('e')
INSERT #T2 VALUES ('f')
SELECT A, B
FROM
(
SELECT ROW_NUMBER() OVER (ORDER BY A ASC) AS RowNo, A
FROM #T1
) t1
JOIN
(
SELECT ROW_NUMBER() OVER (ORDER BY B ASC) AS RowNo, B
FROM #T2
) t2 ON t1.RowNo = t2.RowNo

How will the system know to associate the 'a' value from table1 with the 'd' value from table 2? If someone adds another row to table2 with value 'c' should your query now output
null- c
a - d
b - e
c - f
or
a - c
b - d
c - e
or
a - c
b - d
c - e
null- f
??? --- You have to specify in some way what rules to use to associate the rows from table1 with the rows from table2.
If you just want the rows associated based on alphabetical sorting,
then if the values are unique in each of the tables, (using standard SQL only), try this
Select Z1.ColumnA, z2.ColumnB
From (Select ColumnA,
(Select Count(*)
From Table1
Where ColumnA < t1.ColumnA) RowNo,
From Table1 T1) z1
Join (Select ColumnB,
(Select Count(*)
From Table2
Where ColumnB < t2.ColumnB) RowNo,
From Table2 T2) z2
On z1.RowNo = z2.RowNo
Order By z1.RowNo

Related

SQL Server : add a new column using union

I have 2 tables which have 2 columns in common and 1 column is different in both table
Table A
Table B
I need to create a common table having the values as follows
Expected Output
I tried using join on Memid and Meas but it duplicates as the 2 field do not create unique set as shown in figure
I tried union but then I get a resultset like this
Output for Inner join with distinct condition
How do I go about achieving the desired result set?
Note: Just a note coincidentally in this case the 2 columns seems to have similar values but they can be different.
Basically I need to create this one table with the 4 columns where Payer and PPayer columns should be independent of each other.
You don't need to use UNION, you can try like following using INNER JOIN.
INSERT INTO NewTable (
UserId
,DEPT
,ROOM
,LAB
)
SELECT DISTINCT ta.UserId
,ta.DEPT
,ta.ROOM
,tb.LAB
FROM TableA ta
INNER JOIN TableB tb ON ta.UserId = tb.UserId
AND ta.DEPT = tb.DEPT
Check Working Demo
Shanawaz Khan, Try this Solution
Declare Sample Table
DECLARE #A as TABLE(
UserId INT,
DEPT VARCHAR(50),
ROOM INT)
DECLARE #B as TABLE(
UserId INT,
DEPT VARCHAR(50),
LAB VARCHAR(50))
Insert Sample Records in Created Table
INSERT INTO #A (UserId,DEPT,ROOM) VALUES(1,'A',1),(1,'B',1),(1,'A',2),(1,'B',2)
INSERT INTO #B (UserId,DEPT,LAB) VALUES(1,'A','P'),(1,'B','Q'),(1,'A','P'),(1,'B','Q')
Generate DEPT wise Row number for Both Tables and Insert into another Temptable
SELECT ROW_NUMBER() OVER(PARTITION BY A.DEPT ORDER BY A.ROOM ) AS Rno,* INTO #tbl_A FROM #A A
SELECT ROW_NUMBER() OVER(PARTITION BY B.DEPT ORDER BY B.LAB) AS Rno,* INTO #tbl_B FROM #B B
Final Query Using Inner Join
SELECT A.UserId,A.DEPT,A.ROOM,B.LAB FROM #tbl_A AS A
INNER JOIN #tbl_B AS B ON A.Rno =B.Rno AND A.DEPT =B.DEPT ORDER BY A.ROOM, B.DEPT
Drop Created Temptable
DROP TABLE #tbl_A,#tbl_B
OutPut

Order by first row,last row and rest with 2 tables in SQL Server 2017

I have following two tables. I need to merge 2 tables based also sorted on
few conditions.
DROP TABLE IF EXISTS #t1
CREATE TABLE #t1
(
id INT IDENTITY PRIMARY KEY,
value INT
)
DROP TABLE IF EXISTS #t2
CREATE TABLE #t2
(
id INT IDENTITY PRIMARY KEY,
value int
)
INSERT INTO #t1 (value)
VALUES (1), (30), (19), (10), (40);
INSERT INTO #t2 (value)
VALUES (100), (70), (20);
SELECT * FROM #t1
UNION
SELECT * FROM #t2
I need to union 2 tables and sorted value based on below condition
#t1 first row (fixed)
#t1 last row (fixed)
#t1 rest (other than first row) based on value
4 #t2 only sorted based on value
Expected output:
why are you using varchar to store numeric value ? you will need to perform a cast() or convert() before you will be to sort it.
Assumption : by first or last you are referring with row with minimum and maximum value in column id.
select value, seq as [order]
from
(
select id, value,
seq = case when row_number() over(order by id) = 1 then 1
when row_number() over(order by id desc) = 1 then 2
else 3
end
from #t1
union all
select id, value, seq = 4
from #t2
) d
order by seq, convert(int, value)
You can check this below logic of ordering the output using CASE statement in the ORDER clause-
SELECT *
FROM
(
select 'T1' T_Name,* from #t1
union
select 'T2',* from #t2
)A
ORDER BY
CASE
WHEN t_name = 'T1' AND id = (SELECT MIN(ID) FROM #t1) THEN 1
WHEN t_name = 'T2' AND id = (SELECT MAX(ID) FROM #t2) THEN 2
WHEN t_name = 'T1' THEN 3
ELSE 4
END,
Id -- Or you can order by Value. Just keep in mind that Value is VARCHAR as per your setup. So, Ordering will be also impact accordingly.

SQL Server: How to select top rows of a group based on value of the column of that group?

I have two tables like below.
table 1
id rem
1 2
2 1
table 2
id value
1 abc
1 xyz
1 mno
2 mnk
2 mjd
EDIT:
#output
id value
1 abc
1 xyz
2 mnk
What i want to do is select top 2 rows of table2 with id one as rem value is 2 for id 1 and top 1 row with id 2 as its rem value is 1 and so on. I am using MS sqlserver 2012 My whole scenario is more complex than this. Please help.
Thank you.
EDIT : I know that i should have given what i have done and how i am doing it but for this particular part i don't have idea for starting. I could do this by using while loop for each unique id but i want to do it in one go if possible.
First, SQL tables represent unordered sets. There is no specification of which values you get, unless you include an order by.
For this purpose, I would go with row_number():
select t2.*
from table1 t1 join
(select t2.*,
row_number() over (partition by id order by id) as seqnum
from table2 t2
) t2
on t1.id = t2.id and t2.seqnum <= t1.rem;
Note: The order by id in the windows clause should be based on which rows you want. If you don't care which rows, then order by id or order by (select null) is fine.
Try This:
DECLARE #tbl1 TABLE (id INT, rem INT)
INSERT INTO #tbl1 VALUES (1, 2), (2, 1)
DECLARE #tbl2 TABLE (id INT, value VARCHAR(10))
INSERT INTO #tbl2 VALUES (1, 'abc'), (1, 'xyz'),
(1, 'mno'), (2, 'mnk'), (2, 'mjd')
SELECT * FROM #tbl1 -- your table 1
SELECT * FROM #tbl2 -- your table 2
SELECT id,value,rem FROM ( SELECT ROW_NUMBER() OVER (PARTITION BY T.ID ORDER BY T.ID) rowid,
T.id,T.value,F.rem FROM #tbl2 T LEFT JOIN #tbl1 F ON T.id = F.id ) A WHERE rowid = 1
-- your required output
Hope it helps.

Insert numbers in table in sequence but without IDENTITY set

I have few tables, in one of them I am doing load from excel file and then i am doing insert from select
In target table i have column id which doesn't have IDENTITY on it and i cannot create it, so I used ROW_NUMBER() in my select for INSERT,
however now I am having problem, when next time I'm doing load from file into my temp table from which I am selection data for INSERT row number starts from 1 and if iam trying to do insert i am getting error obout problems with Primary key/ So i need to add ID based on id which is already in target table
for example if in target table last record 1000
first record from new Insert has to have id 1001
INSERT INTO table1
( Id ,
OkeiId ,
OkpdId ,
OkvedId ,
)
SELECT
-- (SELECT MAX (id) FROM table1) AS 'last id in table',
ROW_NUMBER() OVER ( ORDER BY ( SELECT 0 ) ) AS Row , -- Id - int
a.[Id] AS OkeId , - int
c.[Id] AS OkpId , - int
D.[Id] AS OkvId , - int
FROM [dbo].#table b
LEFT OUTER JOIN table2 a ON b.F6 = a.[NationalSymbol]
LEFT OUTER JOIN table3 c ON b.F4 = c.Code
LEFT OUTER JOIN table4 D ON b.F5 = D.Code
LEFT OUTER JOIN table1 f ON b.f1 = f.Code
WHERE f.code IS NULL
any Ideas how to continue insert id in sequence? I CANNOT use IDENTITY on this table. I hope you can understand my explanetions
INSERT INTO table1
( Id ,
OkeiId ,
OkpdId ,
OkvedId
)
SELECT
-- (SELECT MAX (id) FROM table1) AS 'last id in table',
a.last_id + ROW_NUMBER() OVER ( ORDER BY ( SELECT 0 ) ) AS Row , -- Id - int
a.[Id] AS OkeiId , -- OkeiId - int
c.[Id] AS OkpdId , -- OkpdId - int
D.[Id] AS OkvedId -- OkvedId - int
FROM [dbo].#table b
LEFT OUTER JOIN table2 a ON b.F6 = a.[NationalSymbol]
LEFT OUTER JOIN table3 c ON b.F4 = c.Code
LEFT OUTER JOIN table4 D ON b.F5 = D.Code
LEFT OUTER JOIN table1 f ON b.f1 = f.Code
CROSS JOIN (SELECT MAX (id) AS last_id FROM table1 ) a
WHERE f.code IS NULL
and some tests:
CREATE TABLE #a
(
a INT PRIMARY KEY,
aa int
)
CREATE TABLE #b
(
b int
)
INSERT INTO #a VALUES(1,1);
INSERT INTO #b VALUES(1);
INSERT INTO #b VALUES(2);
INSERT INTO #b VALUES(3);
INSERT INTO #b VALUES(4);
INSERT INTO #b VALUES(5);
INSERT INTO #a
SELECT last_id + ROW_NUMBER() OVER(ORDER BY b.b), b.b FROM #b b CROSS JOIN (SELECT MAX(a) last_id FROM #a) a
If you're unable to use IDENTITY for some reason and are on SQL Server 2012+, consider sequence numbers. They can be used with multiple columns/tables and are generally more flexible than IDENTITY. See below for examples of creation and use.
Sequence create
CREATE SEQUENCE TestSequence
AS INTEGER
START WITH 1
INCREMENT BY 1;
Sequence use
CREATE TABLE TestTable
(
TestId INTEGER NOT NULL,
TestColumn CHAR(1) NULL
);
INSERT INTO TestTable (TestId, TestColumn)
VALUES (NEXT VALUE FOR TestSequence, 'A');
SQL Fiddle

Combine two tables in SQL Server

I have tow tables with the same number of rows
Example:
table a:
1,A
2,B
3,C
table b:
AA,BB
AAA,BBB,
AAAA,BBBB
I want a new table made like that in SQL SErver:
1,A,AA,BB
2,B,AAA,BBB
3,C,AAAA,BBBB
How do I do that?
In SQL Server 2005 (or newer), you can use something like this:
-- test data setup
DECLARE #tablea TABLE (ID INT, Val CHAR(1))
INSERT INTO #tablea VALUES(1, 'A'), (2, 'B'), (3, 'C')
DECLARE #tableb TABLE (Val1 VARCHAR(10), Val2 VARCHAR(10))
INSERT INTO #tableb VALUES('AA', 'BB'),('AAA', 'BBB'), ('AAAA', 'BBBB')
-- define CTE for table A - sort by "ID" (I just assumed this - adapt if needed)
;WITH DataFromTableA AS
(
SELECT ID, Val, ROW_NUMBER() OVER(ORDER BY ID) AS RN
FROM #tablea
),
-- define CTE for table B - sort by "Val1" (I just assumed this - adapt if needed)
DataFromTableB AS
(
SELECT Val1, Val2, ROW_NUMBER() OVER(ORDER BY Val1) AS RN
FROM #tableb
)
-- create an INNER JOIN between the two CTE which just basically selected the data
-- from both tables and added a new column "RN" which gets a consecutive number for each row
SELECT
a.ID, a.Val, b.Val1, b.Val2
FROM
DataFromTableA a
INNER JOIN
DataFromTableB b ON a.RN = b.RN
This gives you the requested output:
You could do a rank over the primary keys, then join on that rank:
SELECT RANK() OVER (table1.primaryKey),
T1.*,
T2.*
FROM
SELECT T1.*, T2.*
FROM
(
SELECT RANK() OVER (table1.primaryKey) [rank], table1.* FROM table1
) AS T1
JOIN
(
SELECT RANK() OVER (table2.primaryKey) [rank], table2.* FROM table2
) AS T2 ON T1.[rank] = T2.[rank]
Your query is strange, but in Oracle you can do this:
select a.*, tb.*
from a
, ( select rownum rn, b.* from b ) tb -- temporary b - added rn column
where a.c1 = tb.rn -- assuming first column in a is called c1
if there is not column with numbers in a you can do same trick twice
select ta.*, tb.*
from ( select rownum rn, a.* from a ) ta
, ( select rownum rn, b.* from b ) tb
where ta.rn = tb.rn
Note: be aware that this can generate random combination, for example
1 A AA BB
2 C A B
3 B AAA BBB
because there is no order by in ta and tb

Resources