Build string from a SELECT statement [duplicate] - sql

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
SQL Server Group Concat with Different characters
I need an example on SELECT where the output is a ',' separated string
e.g. SELECT (... something ...) name AS output FROM name_table
gives me
output
-----------------------------
'Ann', 'Tom', 'Wilson', .....
How would you do that in SQL server 2008 R2?
Thank you!

Assuiming you have a schema like this,
CREATE TABLE Table1
([GROUP_ID] int, [PERSON_NAME] varchar(6));
INSERT INTO Table1
([GROUP_ID], [PERSON_NAME])
VALUES
(1001, 'ALEX'),
(1002, 'MATHEW'),
(1001, 'GEORGE'),
(1002, 'THOMAS'),
(1001, 'JAMES');
create a query something like this to produce a comma separated value,
SELECT
GROUP_ID,
STUFF(
(SELECT ', ' + PERSON_NAME
FROM Table1
WHERE [GROUP_ID] = a.GROUP_ID
FOR XML PATH (''))
, 1, 1, '') AS NamesList
FROM Table1 AS a
GROUP BY GROUP_ID
SQLFiddle Demo

Related

How to get delta records using pure SQL?

I have two tables T_Person and T_Person_New in Oracle SQL.
For ease, lets take Name as the unique identifier of both tables.
Can i Compare both tables to get the delta records using an SQL query?
The delta records should consist of the following condition:
If it is a change in an existing record. I.e. a change in DOB / Gender / Name
If its a new record.
Thanks.
We can try using an EXISTS clause here:
SELECT ID, Name, DOB, Gender
FROM T_Person_New t1
WHERE NOT EXISTS (SELECT 1 FROM T_Person t2
WHERE t1.Name = t2.Name AND t1.DOB = t2.DOB AND t1.Gender = t2.Gender);
The logic here is to return every new record for which we cannot find an exactly matching record in the original table. This covers the case that the person already exists, but one or more of the fields have changed. And it also covers the case where the person is completely new, and did not even exist previously.
I have added one more record each in your sample data for old (t_person) and new (t_person_new) tables to cover for missing records from either tables.
I assume that id column is primary key in both tables (it's not clear from you description although you did mention name is unique).
old table sample data
insert into t_person values (1, 'Tom', '2000-01-01', 'M');
insert into t_person values (2, 'Gary', '2000-01-01', 'M');
insert into t_person values (3, 'Pam', '2000-01-01', 'F');
insert into t_person values (4, 'Hans', '2000-01-01', 'M');
new table sample data
insert into t_person_new values (1, 'Tom', '2000-01-01', 'M');
insert into t_person_new values (2, 'Gary', '2001-01-01', 'F');
insert into t_person_new values (3, 'Pamela', '2000-01-01', 'F');
insert into t_person_new values (5, 'Jane', '2000-01-02', 'F');
Here is a query that could show you all possible differences. I have done it only on name column, you can expand it for all columns.
select case when t.id is null then 'NEW: MISSING-FROM-OLD'
else case when tn.id is null then 'DELETED: MISSING-FROM-NEW'
else 'EXISTS-IN-BOTH'
end
end record_type
,case when tn.name is null then 'MISSING-FROM-NEW, VALUE-IN-OLD (' + t.name + ')'
else case when t.name is null then 'MISSING-FROM-OLD, VALUE-IN-NEW (' + tn.name + ')'
else case when t.name = tn.name then 'SAME-IN-BOTH (' + t.name +')'
else 'CHANGED, VALUE-IN-OLD (' + t.name + '), VALUE-IN-NEW (' + tn.name +')'
end
end
end name_state
from t_person_new tn
full outer join t_person t on tn.id = t.id
Note: for Oracle you will have to use '||' instead of '+' to concatenate. I used '+' as I have SQL Server

Displaying multiple row values in one row in SQL Server [duplicate]

This question already has answers here:
Simulating group_concat MySQL function in Microsoft SQL Server 2005?
(12 answers)
Concatenate one field after GROUP BY
(1 answer)
Closed 8 years ago.
I have a table as follow:
ID User Activity PageURL
1 Me act1 ab
2 Me act1 cd
3 You act2 xy
4 You act2 st
I want to group by User and Activity such that I end up with something like:
User Activity PageURL
Me act1 ab, cd
You act2 xy, st
As you can see, the column PageURL is combined together separated by a comma based on the group by.
Would really appreciate any pointers and advice.
SELECT
[User], Activity,
STUFF(
(SELECT DISTINCT ',' + PageURL
FROM TableName
WHERE [User] = a.[User] AND Activity = a.Activity
FOR XML PATH (''))
, 1, 1, '') AS URLList
FROM TableName AS a
GROUP BY [User], Activity
SQLFiddle Demo
A good question. Should tell you it took some time to crack this one. Here is my result.
DECLARE #TABLE TABLE
(
ID INT,
USERS VARCHAR(10),
ACTIVITY VARCHAR(10),
PAGEURL VARCHAR(10)
)
INSERT INTO #TABLE
VALUES (1, 'Me', 'act1', 'ab'),
(2, 'Me', 'act1', 'cd'),
(3, 'You', 'act2', 'xy'),
(4, 'You', 'act2', 'st')
SELECT T1.USERS, T1.ACTIVITY,
STUFF(
(
SELECT ',' + T2.PAGEURL
FROM #TABLE T2
WHERE T1.USERS = T2.USERS
FOR XML PATH ('')
),1,1,'')
FROM #TABLE T1
GROUP BY T1.USERS, T1.ACTIVITY

How to create a query to join multiple rows from a different table into single comma delimated column in SQL Server [duplicate]

This question already has answers here:
Simulating group_concat MySQL function in Microsoft SQL Server 2005?
(12 answers)
Closed 4 years ago.
I am using SQL Server 2014, and I have two tables:
number id
------------------
36-23 1
36-23 2
id value
------------------
1 asia
2 europe
The number column is of type varchar. I want to write a query to return the following results:
number Name
---------------------------
36-23 asia,europe
I am wondering how can I do this with the help of query or functions in SQL Server.
I think using STUFF is the easiest way to go forward here.
CREATE TABLE tableID
([number] varchar(50), [id] int)
;
INSERT INTO tableID
([number], [id])
VALUES
('36-23', 1),
('36-23', 2)
;
CREATE TABLE tableLoc
([id] int, [value] varchar(50))
;
INSERT INTO tableLoc
([id], [value])
VALUES
(1, 'asia'),
(2, 'europe')
;
SELECT tableID.number, tableLoc.value INTO temp1
FROM tableID INNER JOIN tableLoc ON tableID.id = tableLoc.id;
SELECT *, STUFF((
SELECT DISTINCT ', ' + value
FROM temp1
WHERE number = t.number
FOR XML PATH('')), 1, 2, '')
FROM (
SELECT DISTINCT number
FROM temp1
) t

extract all the rows from one field then store in one row based on the name [duplicate]

This question already has answers here:
Simulating group_concat MySQL function in Microsoft SQL Server 2005?
(12 answers)
Closed 8 years ago.
I want to store everything in column Lesion into one row.
Is it possible to do that?
How can I do that?
any advice would help!
try this
DECLARE #source TABLE ( name VARCHAR(100), lesion VARCHAR(20));
INSERT INTO #source(name , lesion)
VALUES ('Bob Desk', '123-456-7899'),
('Bob Desk', '123-456-7899'),
('Don Mouse', '123-456-5555'),
('Mike Keyboard', '123-456-7899'),
('Billy Power', '122-222-1134')
SELECT DISTINCT name,STUFF(
(SELECT ',' + lesion
FROM #source s
WHERE s.name = s2.name
FOR XML PATH (''))
, 1, 1, '')
FROM #source s2

Inserting multiple rows in a single SQL query? [duplicate]

This question already has answers here:
Insert multiple rows WITHOUT repeating the "INSERT INTO ..." part of the statement?
(17 answers)
Closed 9 years ago.
I have multiple set of data to insert at once, say 4 rows. My table has three columns: Person, Id and Office.
INSERT INTO MyTable VALUES ("John", 123, "Lloyds Office");
INSERT INTO MyTable VALUES ("Jane", 124, "Lloyds Office");
INSERT INTO MyTable VALUES ("Billy", 125, "London Office");
INSERT INTO MyTable VALUES ("Miranda", 126, "Bristol Office");
Can I insert all 4 rows in a single SQL statement?
In SQL Server 2008 you can insert multiple rows using a single SQL INSERT statement.
INSERT INTO MyTable ( Column1, Column2 ) VALUES
( Value1, Value2 ), ( Value1, Value2 )
For reference to this have a look at MOC Course 2778A - Writing SQL Queries in SQL Server 2008.
For example:
INSERT INTO MyTable
( Column1, Column2, Column3 )
VALUES
('John', 123, 'Lloyds Office'),
('Jane', 124, 'Lloyds Office'),
('Billy', 125, 'London Office'),
('Miranda', 126, 'Bristol Office');
If you are inserting into a single table, you can write your query like this (maybe only in MySQL):
INSERT INTO table1 (First, Last)
VALUES
('Fred', 'Smith'),
('John', 'Smith'),
('Michael', 'Smith'),
('Robert', 'Smith');
NOTE: This answer is for SQL Server 2005. For SQL Server 2008 and later, there are much better methods as seen in the other answers.
You can use INSERT with SELECT UNION ALL:
INSERT INTO MyTable (FirstCol, SecondCol)
SELECT 'First' ,1
UNION ALL
SELECT 'Second' ,2
UNION ALL
SELECT 'Third' ,3
...
Only for small datasets though, which should be fine for your 4 records.
INSERT statements that use VALUES syntax can insert multiple rows. To do this, include multiple lists of column values, each enclosed within parentheses and separated by commas.
Example:
INSERT INTO tbl_name (a,b,c) VALUES(1,2,3),(4,5,6),(7,8,9);