SQL inserted value of a table as column of another table - sql

Table1 Table2
Id Name Id Table1Id Value
1 Some 1 1 value1
2 Some1 2 2 value2
3 Some2 3 3 value3
4 Some3
.
.
I want to result this:
Some Some1 Some2 Some3
value1 value2 value3 NULL
When I entered value into the Table1 I want to look like the table2's column, how can I do this?
I guess I'm looking for pivot query.

Thanks for posting the additional information. Based on what you said, you're looking for a PIVOT statement that will turn each name in Table1 into a column header, containing the corresponding value from Table2.
Have a look at the following SQL, which produces the output your sample data indicates.
CREATE TABLE #Table1 (ID INT, Name varchar(5))
CREATE TABLE #Table2 (ID INT, Table1ID INT, Value varchar(6))
INSERT INTO #Table1 (ID, Name) SELECT 1, 'Some'
INSERT INTO #Table1 (ID, Name) SELECT 2, 'Some1'
INSERT INTO #Table1 (ID, Name) SELECT 3, 'Some2'
INSERT INTO #Table1 (ID, Name) SELECT 4, 'Some3'
INSERT INTO #Table2 (ID, Table1ID, Value) SELECT 1, 1, 'Value1'
INSERT INTO #Table2 (ID, Table1ID, Value) SELECT 2, 2, 'Value2'
INSERT INTO #Table2 (ID, Table1ID, Value) SELECT 3, 3, 'Value3'
-- List of values to be columns
declare #cols nvarchar(max)
select #cols = coalesce(#cols+N',', N'') + quotename(Name) from #Table1 order by ID
PRINT #Cols
declare #query varchar(MAX)
SET #query = '
SELECT *
FROM
(
SELECT T1.Name, T2.Value
FROM
#Table1 T1
INNER JOIN
#Table2 T2 ON
T1.ID = T2.Table1ID
) s
PIVOT
(
MAX(Value) FOR Name IN ('+#Cols+')
) p'
PRINT #query
EXEC (#query)
DROP TABLE #Table1
DROP TABLE #Table2

Related

Select rows from two tables only whenn 'all in'

I've got the following tables
Table1
Col1 | Col2
r1c1 | r1c2
r2c1 | r2c2
r3c1 | r3c2
r4c1 | r4c2
Table2
Col1_Table1 | Col2
r1c1_table1 | r1c2
r2c1_table1 | r2c2
r3c1_table1 | r3c2
So you see my row #4 is missing in Table2.
Select all rows from table 1 and join table 2. No Problem
But what looks the select like when I want to select all from Table1 but only if all from Table1 are in Table2? I hope you can understand.
In my example I the result of the select has to be zero/null.
If I understand you correctly, you want to return all rows of table 1 only if all of table 1 also exists in table 2
So in effect:
SELECT * FROM #table1
WHERE
(SELECT COUNT(*) FROM #table1)
= (SELECT COUNT(*) FROM #Table1 INNER JOIN #Table2 ON #Table1.col1 = #Table2.col1)
Is that correct? in which case a better way of doing this would be:
SELECT *
FROM #table1
WHERE NOT EXISTS (
SELECT 1
FROM #table1
WHERE col1 NOT IN (SELECT col1 FROM #table2)
);
Hi Please see example below
IF OBJECT_ID('tempdb..#Table1') IS NOT NULL
BEGIN
DROP TABLE #Table1
END
IF OBJECT_ID('tempdb..#Table2') IS NOT NULL
BEGIN
DROP TABLE #Table2
END
CREATE TABLE #Table1 (
Col1 NVARCHAR(20)
, Col2 NVARCHAR(20)
)
INSERT INTO #Table1 VALUES ('r1c1', 'r1c2')
INSERT INTO #Table1 VALUES ('r2c1', 'r2c2')
INSERT INTO #Table1 VALUES ('r3c1', 'r3c2')
INSERT INTO #Table1 VALUES ('r4c1', 'r4c2')
CREATE TABLE #Table2 (
Col1_Table1 NVARCHAR(20)
, Col2 NVARCHAR(20)
)
INSERT INTO #Table2 VALUES ('r1c1_table1','r1c2')
INSERT INTO #Table2 VALUES ('r2c1_table1','r2c2')
INSERT INTO #Table2 VALUES ('r3c1_table1','r3c2')
SELECT COUNT(*) as 'Result'
FROM #Table1 AS t1
INNER JOIN #Table2 AS t2
ON t1.Col1 = t2.Col2
IF OBJECT_ID('tempdb..#Table1') IS NOT NULL
BEGIN
DROP TABLE #Table1
END
IF OBJECT_ID('tempdb..#Table2') IS NOT NULL
BEGIN
DROP TABLE #Table2
END
Hope it helps
I think you are looking for INTERSECT.
Ex:
select Col1, Col2 from table1
INTERSECT
select Col1, Col2 from table2
Intersect will return results based on data being in BOTH tables.
Reference: https://learn.microsoft.com/en-us/sql/t-sql/language-elements/set-operators-except-and-intersect-transact-sql?view=sql-server-2017

SQL Server 2008 - Replace Text Values in Column with Values from Another Table

I've tried flexing my Google-fu to no avail so here I am! Unfortunately I cannot change anything about these tables as they are coming out of an application that I have to report out of.
In SQL Server 2008, I'm trying to replace multiple values in one text string column (Table 1) with the value from another table (Table 2).
Thanks in advance!!
Table 1
id value
-------------
1 a1, a2, a3
2 a2, a3
3 a4
Table 2
id value
---------
a1 Value1
a2 Value2
a3 Value3
a4 Value4
Desired Output
id value
-----------------------------
1 Value1, Value2, Value3
2 Value2, Value3
3 Value4
I'm sorry for this solution in advance :) It does what you need though:
create table TableA(
id int,
string varchar(255)
)
create table table2(
id varchar , text varchar(255)
)
insert into tableA values(1,'a,b,c,d')
insert into tableA values(2,'e,f')
insert into table2 values('a', 'value1')
insert into table2 values('b', 'value2')
insert into table2 values('c', 'value3')
insert into table2 values('d', 'value4')
insert into table2 values('e', 'value5')
insert into table2 values('f', 'value6')
select id, left(myConcat,len(myConcat)-1) from (
select c.id, replace(replace(CAST(CAST('<i'+stuff((select * from(
SELECT A.[id] ,
Split.a.value('.', 'VARCHAR(1000)') AS String
FROM (SELECT [id],
CAST ('<M>' + REPLACE([string], ',', '</M><M>') + '</M>' AS XML) AS String
FROM TableA) AS A CROSS APPLY String.nodes ('/M') AS Split(a)) a
inner join table2 b on a.String = b.id
where a.id = c.id
FOR XML PATH ('')
),1,2,'') AS XML).query('/text') AS VARCHAR(1000)),'<text>',''),'</text>',',') myConcat
from TableA c
group by c.id
) d
Using the DelimitedSplit8K found at http://www.sqlservercentral.com/articles/Tally+Table/72993/ as suggested by #user1221684 you might come up with something like this. Working with delimited data like this is a pain. First you have to parse the string so you can join it to the other table and then ruin by stuffing it back into a denormalized form.
Make sure that if you use this that you understand that function and what this code is doing. This is not entry level t-sql and it will be YOU supporting this at 3am when it breaks in production, not me.
if OBJECT_ID('tempdb..#table1') is not null
drop table #table1;
create table #table1
(
id int,
value varchar(50)
);
insert #table1
select 1, 'a1, a2, a3' union all
select 2, 'a2, a3' union all
select 3, 'a4';
if OBJECT_ID('tempdb..#table2') is not null
drop table #table2;
create table #table2
(
id varchar(50),
value varchar(50)
);
insert #table2
select 'a1', 'Value1' union all
select 'a2', 'Value2' union all
select 'a3', 'Value3' union all
select 'a4', 'Value4';
with parsedValues as
(
select t1.id
, t1.value
, LTRIM(x.item) as item
from #table1 t1
cross apply dbo.DelimitedSplit8K(t1.value, ',') x
)
, swappedVals as
(
select pv.id
, t2.value
from parsedValues pv
join #table2 t2 on t2.id = pv.item
)
select id
, STUFF((select ',' + value
from swappedVals sv2
where sv2.id = sv.id
order by sv2.value --need to make sure to order here so the results are in the right order
for XML path('')), 1, 1, '') as MyValues
from swappedVals sv
group by id
;
This site has a delimited text split function http://www.sqlservercentral.com/articles/Tally+Table/72993/
Use that function to split your values out into a temp table. Replace the values in your temp table with the new values. Then use STUFF..FOR XML to combine the records back together and update your table.
One query with a few cte's should be able to handle all of this after you add the function to your database.
Example using Sql Fiddle
Use this:
DECLARE #t TABLE(id int,value varchar(255))
INSERT INTO #t (id,value)
VALUES(1,'a1'),(2,'a2'),(3,'a3')....
SELECT *,STUFF((SELECT DISTINCT ','+value FROM #t WHERE id=t.id)
FOR XML PATH('')),1,2,' ')
FROM (SELECT DISTINCT ID FROM #t) t
DISTINCT in the case of same id, otherwise let it go

Merge multiple rows into single value using update Query

Here is the scenario. I have two tables. I want to merge multiple row value to single value using update query.
DECLARE #Table as Table
(
id int,
name varchar(10)
)
insert into #Table values(1,'a')
insert into #Table values(1,'b')
insert into #Table values(1,'c')
select * from #Table
DECLARE #Table2 as Table
(
id int,
name varchar(10)
)
insert into #Table2 values(1,'a')
update t2 set name = t1.name from #Table2 t2
inner join #Table t1 on t1.id=t2.id
select * from #Table2
I want output from #Table2 as by using update query
id name
----- --------
1 a,b,c
;WITH Table1 AS (
SELECT t.id
, STUFF((SELECT ',' + name
FROM #Table
WHERE id = t.id
FOR XML PATH(''), TYPE)
.value('.','NVARCHAR(MAX)'),1,1,'') AS name
FROM #Table t
GROUP BY t.id)
UPDATE t2
SET t2.name = t1.name
FROM #Table2 t2
INNER JOIN Table1 t1 ON t1.id=t2.id

I have a SQL table with multiple rows that I want into one row with multiple columns

I have a SQL table that has mulitiple rows of data for a user. I want to query that data and return one row for each user. So I want to take the multiple rows and combine them into one row with multiple columns. Is this possible?
Here is what I currently have
UserID Value
8111 396285
8111 812045789854
8111 Secretary
Here is what I am after
UserID Column1 Column2 Column3
8111 396285 812045789854 Secretary
You can use the PIVOT function to get the result. I used the row_number() function to generate the values that will be converted to columns.
If you know how many values you will have ahead of time, then you can hard-code the query:
select userid, Col1, Col2, Col3
from
(
select userid, value,
'Col'+cast(row_number() over(partition by userid
order by (select 1)) as varchar(10)) rn
from yt
) d
pivot
(
max(value)
for rn in (Col1, Col2, Col3)
) piv;
See SQL Fiddle with Demo.
If you have an unknown number of values, then you can use dynamic SQL:
DECLARE #cols AS NVARCHAR(MAX),
#query AS NVARCHAR(MAX)
select #cols = STUFF((SELECT distinct ',' + QUOTENAME('Col'+cast(row_number() over(partition by userid
order by (select 1)) as varchar(10)))
from yt
FOR XML PATH(''), TYPE
).value('.', 'NVARCHAR(MAX)')
,1,1,'')
set #query = 'SELECT userid,' + #cols + '
from
(
select userid, value,
''Col''+cast(row_number() over(partition by userid
order by (select 1)) as varchar(10)) rn
from yt
) x
pivot
(
max(value)
for rn in (' + #cols + ')
) p '
execute(#query);
See SQL Fiddle with Demo. Both give the result:
| USERID | COL1 | COL2 | COL3 |
----------------------------------------------
| 8111 | 396285 | 812045789854 | Secretary |
If you cannot or don't want to use PIVOT/UNPIVOT another option would be to join the columns one by one to the users:
DECLARE #Users TABLE(
UserID int NOT NULL
)
INSERT INTO #Users (UserID) VALUES (1)
INSERT INTO #Users (UserID) VALUES (2)
INSERT INTO #Users (UserID) VALUES (3)
DECLARE #AnyTable TABLE(
UserID int NOT NULL,
FieldNo int NOT NULL,
Value varchar(50) NULL
)
INSERT INTO #AnyTable (UserID, FieldNo, Value) VALUES (1, 1, 'abc')
INSERT INTO #AnyTable (UserID, FieldNo, Value) VALUES (1, 2, 'def')
INSERT INTO #AnyTable (UserID, FieldNo, Value) VALUES (1, 3, 'ghi')
INSERT INTO #AnyTable (UserID, FieldNo, Value) VALUES (2, 1, '123')
INSERT INTO #AnyTable (UserID, FieldNo, Value) VALUES (2, 3, '789')
SELECT u.UserID,
col1.Value as Column1,
col2.Value as Column2,
col3.Value as Column3
FROM #Users u
LEFT JOIN #AnyTable col1
ON col1.UserID = u.UserID
AND col1.FieldNo = 1
LEFT JOIN #AnyTable col2
ON col2.UserID = u.UserID
AND col2.FieldNo = 2
LEFT JOIN #AnyTable col3
ON col3.UserID = u.UserID
AND col3.FieldNo = 3
The result would be:
UserID Column1 Column2 Column3
1 abc def ghi
2 123 NULL 789
3 NULL NULL NULL

Finding One record from table having unique PK and duplicate FK

I want one record from a table having unique Primary Key and duplicate Foreign Key
Please see attached image below
alt text http://img413.imageshack.us/img413/9940/findduplicate.png
Thanks
Select fk, Count(*)
from table1
group by fk
having count(*) > 1
Primary key by definition means there will only be one, so your question appears to actually appears to be are the any rows with more than 1 child row:
select *
from table1 t
where exists (
select id from table2 t2
where t2.fkid = t.id
group by t2.id
having count(*) > 1
)
This would retrieve all unique fk and textVal values from the table:
select distinct fk, textVal from myTable
Have a look at this example.
This will find you all IDs from TABLE1 where it is duplicated in TABLE2 as a FOREIGN KEY
DECLARE #Table1 TABLE(
id INT
)
DECLARE #Table2 TABLE(
id INT,
fkid INT
)
INSERT INTO #Table1 (id) SELECT 1
INSERT INTO #Table1 (id) SELECT 2
INSERT INTO #Table1 (id) SELECT 3
INSERT INTO #Table2 (id,fkid) SELECT 1, 1
INSERT INTO #Table2 (id,fkid) SELECT 2, 2
INSERT INTO #Table2 (id,fkid) SELECT 3, 2
INSERT INTO #Table2 (id,fkid) SELECT 4, 3
INSERT INTO #Table2 (id,fkid) SELECT 5, 3
INSERT INTO #Table2 (id,fkid) SELECT 6, 3
SELECT t2.fkid
FROM #Table2 t2
GROUP BY t2.fkid
HAVING COUNT(t2.fkid) > 1