This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Concatenate many rows into a single text string?
How to use GROUP BY to concatenate strings in SQL Server?
I have a table customer (id, person_id, account number), id is primary key. For example
id person_id account number
1 0001 acc00011
2 0001 acc00012
3 0002 acc00021
Now I want to write a query to self join the table to get all the account numbers for each person. The result table should be
person_id account
0001 acc00011, acc00012
0002 acc00021
How do I write the query?
You can't do that unless you want accounts concatenated in a single string by person_id.
See this questions:
How to create a SQL Server function to "join" multiple rows from a subquery into a single delimited field?
Concatenate many rows into a single text string?
How to use GROUP BY to concatenate strings in SQL Server?
Use a correlated subquery with FOR XML PATH and GROUP BY for the concatenation. Use STUFF to remove preceding comma from results.
See example here: http://sqlfiddle.com/#!3/e5bd0/5
Related
This question already has answers here:
Simulating group_concat MySQL function in Microsoft SQL Server 2005?
(12 answers)
MSSQL - GROUP_CONCAT
(1 answer)
I want to do group_concat in SQL Server
(1 answer)
Closed 2 years ago.
I have a bit of an issue. I have a dataset with around 6000 records stored in a MSSQL 2016 database, where I need to concatenate each column, sorted on row basis and grouped by an ID.
It is no problem to sort the data within the column itself, but the position of the concatenated values is the key in the system that needs the data. So, if I merge four rows with the same ID, each row value must be in the same position throughout the whole resultset row.
To make it even more messy, I must be able to apply some logic to determine which row should be in position one.
If I use the the sort functionality in GROUP_CONCAT_DS (I'm using a semicolon delimiter), it sorts on the column values, which make the index position of each merge inconsistent related to the rows that holds the data.
Example data:
id col1 col2
--------------------
1 foo bar
1 lorem ipsum
2 hi cowboy
Expected output:
id, concat_col1, concat_col2
----------------------------
1 foo;lorem bar;ipsum
2 hi cowboy
Absolutely unacceptable output:
id concat_col1 concat_col2
----------------------------
1 bar;foo lorem;ipsum
2 hi cowboy
In pseudo-SQL, this is a simplified example of what I want to achieve:
SELECT
[id]
,dbo.GROUP_CONCAT_D([col1], ';') AS [concat_col1]
,dbo.GROUP_CONCAT_D([col2], ';') AS [concat_col2]
FROM [hrm].[vEmploymentsPositions]
GROUP BY [id]
ORDER BY [id] asc, [col1] desc, [col2] asc
... But for loical reason the sort doesn't work that way.
How can I approach this issue and make a robust solution that fit our needs?
I have 2 tables: "table1" and "table2" and in these tables, I have hundred of names. Now I want to select only these names, where first 4 character have the same value.
So far it is not so difficult. Something like this:
select * from table1
join table2 on LEFT(table1.name,4)=LEFT(table2.name,4)
But I am struggling to add one condition that some characters have same value, for example: i=y, v=w, c=k and vice versa.
If table1 has name "Citty" and table2 has name "Kitty", I want this name also comes out in results
You should look into SOUNDEX() and DIFFERENCE() functions of SQL Server. These are available with full text search.
Alternatively, you can create a clr function and call it from sql.
I've searched for long time for getting last entered data in a table. But I got same answer.
SELECT TOP 1 CustomerName FROM Customers
ORDER BY CustomerID DESC;
My scenario is, how to get last data if that Customers table is having CustomerName column only? No other columns such as ID or createdDate I entered four names in following order.
James
Arun
Suresh
Bryen
Now I want to select last entered CustomerName, i.e., Bryen. How can I get it..?
If the table is not properly designed (IDENTITY, TIMESTAMP, identifier generated using SEQUENCE etc.), INSERT order is not kept by SQL Server. So, "last" record is meaningless without some criteria to use for ordering.
One possible workaround is if, by chance, records in this table are linked to some other table records (FKs, 1:1 or 1:n connection) and that table has a timestamp or something similar and you can deduct insertion order.
More details about "ordering without criteria" can be found here and here.
; with cte_new as (
select *,row_number() over(order by(select 1000)) as new from tablename
)
select * from cte_new where new=4
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Concatenate a selected column in a single query?
I know this is fairly simple in MySQL, but i don't know how to do it in SQLServer. I have a table containing two columns. UserID & TagID. I'd like to concatenate TagID into a comma separated string, where the result is grouped by UserID. How can i do that?
I would ythink something lik ethis might be what you are looking for :
SELECT ''+Table1.UserID+','+Table2.TagID+'' AS CombinedCSVColumn
, SUM(Table1.Value) AS Value
From dbo.Table1 as Table1
INNER JOIN db.Table2 as Table2
ON Table1.EmployeeID = Table2.EmployeeID
GROUP BY ''+Table1.UserID+','+Table2.TagID+''
That is if they come from two Tables. For one table is similar.
Regards
Mac
On SQL Server, executing the following SQL Statement:
SELECT 1,2,3
will return
(no column name) (no column name) (no column name)
1 2 3
Note that the columns don't have names and the number of columns is not definite (it can have 1 column or it can also have > 100 columns).
My question is - Does anybody know of a simple approach so I can get the following result:
(no column name)
1
2
3
What I'm really trying to do is come up with a SQL similar to the one below. I wish I could execute it as it is but of course we know that the Select 1,2,3 won't work, we have to somehow transform that into a table with the values in each row.
SELECT *
FROM NORTHWIND.DBO.CUSTOMERS
WHERE EMPLOYEEID IN (*Select 1,2,3*); -- *Select 1,2,3 will not work
Currently I'm thinking of creating a user defined function that returns a table by iterating through each column and dynamically creating multiple SQL statements combined by UNION similar to: SELECT 1 Col1 UNION SELECT 2 UNION SELECT 3. I'm not a fan of dynamic SQL and looping procedures in my queries as it can be expensive to process especially for an application with expected usage of 1000+ per minute. Also, there is that concern for SQL Injection Attacks with Dynamic SQL when I start using strings instead of integer values. I'm also trying to avoid temporary tables as it can even be more expensive to process.
Any ideas? Can we use UNPIVOT without the need for looping through the indefinite number of columns and dynamically creating the SQL text to execute it and transform the columnar values into rows? What about Common Table Expressions?
Get rid of the select and just specify a list of values:
SELECT * FROM NORTHWIND.DBO.CUSTOMERS
WHERE EMPLOYEEID IN (1,2,3);