Concatenate many rows into a single text string - sql

I'm trying to concatenate several names into a single column but I'm having trouble getting there.
DECLARE #Names VARCHAR(8000)
SELECT
p.Pato_Id
#Names = COALESCE(#Names + ', ', '') + e.First_Name + ' ' + e.Last_Name
FROM
Patos p
LEFT JOIN
Pato_Owners po
ON
po.Pato_Id = p.Pato_Id
LEFT JOIN
Person e
ON
po.Owner_Id = e.Person_Id
How can this be done?
EDIT:
When I'm making a normal select I getting
PatoID First Last
0 John Wort
0 Dan Mass
1 Till Bos
2 Wrap Sim
2 Port Lock
And what I want is:
PatoID Names
0 John Wort, Dan Mass
1 Till Bos
2 Wrap Sim, Port Lock

You have left join which indicate that you can have null names. This would reset the values of names should that occur.
;with cte as
(
SELECT
p.Pato_Id,
coalesce(e.First_Name, '') + coalesce(' ' + e.Last_Name, '') Name
FROM
Patos p
LEFT JOIN
Pato_Owners po
ON
po.Pato_Id = p.Pato_Id
LEFT JOIN
Person e
ON
po.Owner_Id = e.Person_Id
)
select t.Pato_id
,STUFF((
select ',' + [name]
from cte t1
where t1.Pato_Id = t.Pato_Id
for xml path(''), type
).value('.', 'varchar(max)'), 1, 1, '') [Names]
from cte t
group by t.Pato_id

Try this,
DECLARE #Names VARCHAR(8000)
SELECT
p.Pato_Id,
'ServerName' = COALESCE(#Names + ', ', '') + e.First_Name + ' ' + e.Last_Name
FROM
Patos p
LEFT JOIN
Pato_Owners po
ON
po.Pato_Id = p.Pato_Id
LEFT JOIN
Person e
ON
po.Owner_Id = e.Person_Id

I think you want this,
WITH Sales_CTE (Pato_Id, First, Last)
AS
(
Select p.Pato_Id , e.First , e.Last
FROM
Patos p
LEFT JOIN
Pato_Owners po
ON
po.Pato_Id = p.Pato_Id
LEFT JOIN
Person e
ON
po.Owner_Id = e.Person_Id
)
SELECT Pato_Id,
Substring((Select ',' + ISNULL(First,'') + ISNULL(Last,'') From Sales_CTE B Where B.Pato_Id=A.Pato_Id For XML Path('')),2,8000) As names
from Sales_CTE A group by Pato_Id;

Related

Need advice. The following changes causes my stored procedure to EXECUTE for 5mins

I have the following view:
ALTER VIEW [dbo].[vAccount]
AS
with cte_accounts_data AS
(
SELECT
null as CompanyVendorAccountId
,CAST(0 as bit) as IsVendorAccount
,null as VendorAccountReference
,null as VendorCompanyId
,a.[AccountId]
,a.[CompanyId]
,a.[CompanyAccountTypeId]
,ag.[CompanyAccountGroupId]
,ag.[Name] as CompanyAccountGroupName
,a.[RegionId]
,a.[Name]
,CONCAT(c.ShortName + ': ', a.[Name], ' [' + a.[Code] +']') AS DisplayName
,a.[Code]
,a.[Address]
,a.[Email]
,a.[IncludeEscalationEmail]
,a.[GPSLat]
,a.[GPSLong]
,a.[Telephone]
,a.[VATNumber]
,a.[AutoReceive]
,a.[AutoIssue]
,a.[IsBillableToAccount]
,a.[BillingStart]
,a.[IsEquipmentDepot]
,a.[IsShiftAttendanceEnabled]
,a.[ShiftMinHoursForLunchDeduction]
,a.[NightShiftStart]
,a.[NightShiftEnd]
,a.[ShiftStartDayOfMonth]
,a.[OperatingHoursStart]
,a.[OperatingHoursEnd]
,a.[LoadBays]
,a.[LoadInterval]
,a.[ArrivalInterval]
,a.[OverrideStockTakeCloseBalanceTime]
--,a.[RFEquipment]
,a.[temp_IgnoreVendorIssueViaSAP]
,a.[Archived]
,a.[CreatedDate]
,a.[CreatedBy_PersonId]
,a.[UpdatedDate]
,a.[UpdatedBy_PersonId]
,cat.Name as CompanyAccountTypeName
,at.Name as AccountTypeName
,at.AccountTypeId
,at.EnumAccountType
,r.Name as Region
,c.Name as Company
,CONCAT(c.Code, ': ', a.Name, ' ',a.Code, ' ', c.Name, ' ', r.Name, ' ', at.Name, ' ', r.Code, ' ') as ViewSearchColumn
FROM
[Account] a
JOIN Company c on (a.CompanyId = c.CompanyId)
JOIN CompanyAccountType cat on (a.CompanyAccountTypeId = cat.CompanyAccountTypeId)
JOIN AccountType at on (cat.AccountTypeId = at.AccountTypeId)
LEFT OUTER JOIN vCompanyAccountGroup ag on (a.CompanyAccountGroupId = ag.CompanyAccountGroupId)
LEFT OUTER JOIN Region r on (a.RegionId = r.RegionId)
UNION
SELECT
cv.[CompanyVendorAccountId]
,CAST(1 as bit) as IsVendorAccount
,cv.[VendorAccountReference]
,a.[CompanyId] as VendorCompanyId
,a.[AccountId]
,cv.[CompanyId]
,cv.[CompanyAccountTypeId]
,ag.[CompanyAccountGroupId]
,ag.[Name] as CompanyAccountGroupName
,a.[RegionId]
,a.[Name]
,CONCAT(c.ShortName + ': ', a.[Name], ' [' + cv.[VendorAccountReference] +']') AS DisplayName
,cv.[VendorAccountReference] as [Code]
,a.[Address]
,a.[Email]
,a.[IncludeEscalationEmail]
,a.[GPSLat]
,a.[GPSLong]
,a.[Telephone]
,a.[VATNumber]
,a.[AutoReceive]
,a.[AutoIssue]
,a.[IsBillableToAccount]
,a.[BillingStart]
,a.[IsEquipmentDepot]
,a.[IsShiftAttendanceEnabled]
,a.[ShiftMinHoursForLunchDeduction]
,a.[NightShiftStart]
,a.[NightShiftEnd]
,a.[ShiftStartDayOfMonth]
,a.[OperatingHoursStart]
,a.[OperatingHoursEnd]
,a.[LoadBays]
,a.[LoadInterval]
,a.[ArrivalInterval]
,a.[OverrideStockTakeCloseBalanceTime]
--,a.[RFEquipment]
,a.[temp_IgnoreVendorIssueViaSAP]
,cv.[Archived]
,cv.[CreatedDate]
,cv.[CreatedBy_PersonId]
,cv.[UpdatedDate]
,cv.[UpdatedBy_PersonId]
,cat.Name as CompanyAccountTypeName
,at.Name as AccountTypeName
,at.AccountTypeId
,at.EnumAccountType
,r.Name as Region
,c.Name as Company
,CONCAT(c.Code, ': ', a.Name, ' ',a.Code, ' ', c.Name, ' ', r.Name, ' ', at.Name, ' ', r.Code, ' ') as ViewSearchColumn
FROM
[CompanyVendorAccount] cv
JOIN Company c on (cv.CompanyId = c.CompanyId)
JOIN CompanyAccountType cat on (cv.CompanyAccountTypeId = cat.CompanyAccountTypeId)
JOIN AccountType at on (cat.AccountTypeId = at.AccountTypeId)
JOIN Account a on (cv.VendorAccountId = a.AccountId)
LEFT OUTER JOIN Region r on (a.RegionId = r.RegionId)
LEFT OUTER JOIN vCompanyAccountGroup ag on (cv.CompanyAccountGroupId = ag.CompanyAccountGroupId)
WHERE
cv.CompanyId != a.CompanyId
)
,cte_ranking_order as
(
SELECT ROW_NUMBER() over (ORDER BY AccountId, CompanyId) as rankNumber,* FROM cte_accounts_data
)
SELECT [CompanyVendorAccountId]
,IsVendorAccount
,[VendorAccountReference]
,[VendorCompanyId]
,[AccountId]
,[CompanyId]
,[CompanyAccountTypeId]
,[CompanyAccountGroupId]
,[CompanyAccountGroupName]
,[RegionId]
,[Name]
,[DisplayName]
,[Code]
,[Address]
,[Email]
,[IncludeEscalationEmail]
,[GPSLat]
,[GPSLong]
,[Telephone]
,[VATNumber]
,[AutoReceive]
,[AutoIssue]
,[IsBillableToAccount]
,[BillingStart]
,[IsEquipmentDepot]
,[IsShiftAttendanceEnabled]
,[ShiftMinHoursForLunchDeduction]
,[NightShiftStart]
,[NightShiftEnd]
,[ShiftStartDayOfMonth]
,[OperatingHoursStart]
,[OperatingHoursEnd]
,[LoadBays]
,[LoadInterval]
,[ArrivalInterval]
,[OverrideStockTakeCloseBalanceTime]
,[temp_IgnoreVendorIssueViaSAP]
,[Archived]
,[CreatedDate]
,[CreatedBy_PersonId]
,[UpdatedDate]
,[UpdatedBy_PersonId]
,[CompanyAccountTypeName]
,[AccountTypeName]
,[AccountTypeId]
,[EnumAccountType]
,[Region]
,[Company]
,[ViewSearchColumn]
FROM cte_ranking_order where rankNumber = 1
GO
Which I modified to look like the above.
Below is the original View:
ALTER VIEW [dbo].[vAccount]
AS
with cte_accounts_data AS
(
SELECT
null as CompanyVendorAccountId
,CAST(0 as bit) as IsVendorAccount
,null as VendorAccountReference
,null as VendorCompanyId
,a.[AccountId]
,a.[CompanyId]
,a.[CompanyAccountTypeId]
,ag.[CompanyAccountGroupId]
,ag.[Name] as CompanyAccountGroupName
,a.[RegionId]
,a.[Name]
,CONCAT(c.ShortName + ': ', a.[Name], ' [' + a.[Code] +']') AS DisplayName
,a.[Code]
,a.[Address]
,a.[Email]
,a.[IncludeEscalationEmail]
,a.[GPSLat]
,a.[GPSLong]
,a.[Telephone]
,a.[VATNumber]
,a.[AutoReceive]
,a.[AutoIssue]
,a.[IsBillableToAccount]
,a.[BillingStart]
,a.[IsEquipmentDepot]
,a.[IsShiftAttendanceEnabled]
,a.[ShiftMinHoursForLunchDeduction]
,a.[NightShiftStart]
,a.[NightShiftEnd]
,a.[ShiftStartDayOfMonth]
,a.[OperatingHoursStart]
,a.[OperatingHoursEnd]
,a.[LoadBays]
,a.[LoadInterval]
,a.[ArrivalInterval]
,a.[OverrideStockTakeCloseBalanceTime]
--,a.[RFEquipment]
,a.[temp_IgnoreVendorIssueViaSAP]
,a.[Archived]
,a.[CreatedDate]
,a.[CreatedBy_PersonId]
,a.[UpdatedDate]
,a.[UpdatedBy_PersonId]
,cat.Name as CompanyAccountTypeName
,at.Name as AccountTypeName
,at.AccountTypeId
,at.EnumAccountType
,r.Name as Region
,c.Name as Company
,CONCAT(c.Code, ': ', a.Name, ' ',a.Code, ' ', c.Name, ' ', r.Name, ' ', at.Name, ' ', r.Code, ' ') as ViewSearchColumn
FROM
[Account] a
JOIN Company c on (a.CompanyId = c.CompanyId)
JOIN CompanyAccountType cat on (a.CompanyAccountTypeId = cat.CompanyAccountTypeId)
JOIN AccountType at on (cat.AccountTypeId = at.AccountTypeId)
LEFT OUTER JOIN vCompanyAccountGroup ag on (a.CompanyAccountGroupId = ag.CompanyAccountGroupId)
LEFT OUTER JOIN Region r on (a.RegionId = r.RegionId)
UNION
SELECT
cv.[CompanyVendorAccountId]
,CAST(1 as bit) as IsVendorAccount
,cv.[VendorAccountReference]
,a.[CompanyId] as VendorCompanyId
,a.[AccountId]
,cv.[CompanyId]
,cv.[CompanyAccountTypeId]
,ag.[CompanyAccountGroupId]
,ag.[Name] as CompanyAccountGroupName
,a.[RegionId]
,a.[Name]
,CONCAT(c.ShortName + ': ', a.[Name], ' [' + cv.[VendorAccountReference] +']') AS DisplayName
,cv.[VendorAccountReference] as [Code]
,a.[Address]
,a.[Email]
,a.[IncludeEscalationEmail]
,a.[GPSLat]
,a.[GPSLong]
,a.[Telephone]
,a.[VATNumber]
,a.[AutoReceive]
,a.[AutoIssue]
,a.[IsBillableToAccount]
,a.[BillingStart]
,a.[IsEquipmentDepot]
,a.[IsShiftAttendanceEnabled]
,a.[ShiftMinHoursForLunchDeduction]
,a.[NightShiftStart]
,a.[NightShiftEnd]
,a.[ShiftStartDayOfMonth]
,a.[OperatingHoursStart]
,a.[OperatingHoursEnd]
,a.[LoadBays]
,a.[LoadInterval]
,a.[ArrivalInterval]
,a.[OverrideStockTakeCloseBalanceTime]
--,a.[RFEquipment]
,a.[temp_IgnoreVendorIssueViaSAP]
,cv.[Archived]
,cv.[CreatedDate]
,cv.[CreatedBy_PersonId]
,cv.[UpdatedDate]
,cv.[UpdatedBy_PersonId]
,cat.Name as CompanyAccountTypeName
,at.Name as AccountTypeName
,at.AccountTypeId
,at.EnumAccountType
,r.Name as Region
,c.Name as Company
,CONCAT(c.Code, ': ', a.Name, ' ',a.Code, ' ', c.Name, ' ', r.Name, ' ', at.Name, ' ', r.Code, ' ') as ViewSearchColumn
FROM
[CompanyVendorAccount] cv
JOIN Company c on (cv.CompanyId = c.CompanyId)
JOIN CompanyAccountType cat on (cv.CompanyAccountTypeId = cat.CompanyAccountTypeId)
JOIN AccountType at on (cat.AccountTypeId = at.AccountTypeId)
JOIN Account a on (cv.VendorAccountId = a.AccountId)
LEFT OUTER JOIN Region r on (a.RegionId = r.RegionId)
LEFT OUTER JOIN vCompanyAccountGroup ag on (cv.CompanyAccountGroupId = ag.CompanyAccountGroupId)
WHERE
cv.CompanyId != a.CompanyId
The only think I added, was this cte:
,cte_ranking_order as
(
SELECT ROW_NUMBER() over (PARTITION BY AccountId, CompanyID ORDER BY AccountId, CompanyId) as rankNumber,* FROM cte_accounts_data
)
The point of this was to only select unique Accounts from the original select lsits, by giving it a ROW_NUMBER() and partitioning the data with over (PARTITION BY AccountId, CompanyID ORDER BY AccountId, CompanyId).
When a stored procedure tries to join this View with some other views, passed in a specific #AccountId, the stored procedure executes for about 5min.
I really am not sure what could posiible cause this?
I was going to add this as a comment, but I couldn't really give you a good example of what I was trying to say...
Have you eliminated SQL's parameter sniffing as the culprit? I've had it happen many times, running the query in a query window is fast, but the sp takes forever. This can happen when parameter sniffing kicks in. You can avoid this by assigning the passed variables to new variables within the SP and then referencing those instead.
So, for example:
CREATE PROCEDURE dbo.MyProcedureName(
#AccountID INT
)
BEGIN
-- Prevent parameter sniffing.
DECLARE #MyAccountID INT = #AccountID;
SELECT
...
FROM dbo.MyView
WHERE
MyView.AccountID = #MyAccountID;
...
END
Just a thought, but this has happened to me before and I beat my head against a wall trying to figure it out.
I know there are other ways (perhaps better) to handle this particular problem, but this solution has always worked for me.
Some additional reading on the subject if interested:
https://www.red-gate.com/simple-talk/sql/t-sql-programming/parameter-sniffing/

SQL Pivot Query for Attendance Report

I have below query written for my attendance report. everything works fine except one thing. i have multiple checkin/checkout allowed in a day in my application now when i run my query it returns checkin, checkout, total, checkin checkout total. the result i expect is something like: checkin, checkout, checkin, checkout.... total.
Below is the query:
SELECT EmployeeID, Employee, [2016-09-01],[2016-09-02],[2016-09-05],[2016-09-06],[2016-09-07],[2016-09-08],[2016-09-09] from
(
SELECT src.EmployeeID, isnull(b.EmployeeName,'') +' '+ isnull(b.LastName,'') Employee
,[CheckinDate]
, ISNULL(CAST(c.LeaveDesc as VARCHAR(max)), STUFF((
SELECT ', ' + CAST(ISNULL(CheckinTime,'') AS VARCHAR(5)) + char(10) + CAST(ISNULL(CheckoutTime,'') AS VARCHAR(5)) +
char(10) + CAST(ISNULL(TotalHours,'') AS VARCHAR(5))
FROM EmployeeDetail
WHERE (EmployeeID = src.EmployeeID and CheckinDate = src.CheckinDate)
FOR XML PATH(''),TYPE).value('(./text())[1]','VARCHAR(MAX)')
,1,2,'')) AS Result
FROM [EmployeeDetail] as src inner join EmployeeMaster b on src.EmployeeID = b.EmployeeID and src.KindergardenID = b.KindergardenID
left outer join leavetype c on src.leaveid = c.leaveid
WHERE src.KindergardenID = 1
GROUP BY src.EmployeeID, isnull(b.EmployeeName,'') +' '+ isnull(b.LastName,''), CheckinDate,LeaveDesc
) x
pivot
(
max(Result)
for CheckinDate in ([2016-09-01],[2016-09-02],[2016-09-05],[2016-09-06],[2016-09-07],[2016-09-08],[2016-09-09])
) p
Any help in changing the query to make it work as expected is appreciated.
Let me know if i was confusing in asking.
SELECT EmployeeID, Employee, ' + #cols + ' from
(
SELECT src.EmployeeID, isnull(b.EmployeeName,'''') +'' ''+ isnull(b.LastName,'''') Employee
,[CheckinDate]
, ISNULL(CAST(c.LeaveDesc as VARCHAR(max)), isnull(left(convert(time,DATEADD(minute,(SUM(DATEDIFF(MINUTE, ''0:00:00'', TotalHours))),0)),5),''N/A'') + char(10) + STUFF((
SELECT '', '' + CAST(ISNULL(CheckinTime,'''') AS VARCHAR(5)) + ''-'' + CAST(ISNULL(CheckoutTime,'''') AS VARCHAR(5)) +
char(10)
FROM EmployeeDetail
WHERE (EmployeeID = src.EmployeeID and CheckinDate = src.CheckinDate)
FOR XML PATH(''''),TYPE).value(''(./text())[1]'',''VARCHAR(MAX)'')
,1,2,'''')) AS Result
FROM [EmployeeDetail] as src inner join EmployeeMaster b on src.EmployeeID = b.EmployeeID and src.KindergardenID = b.KindergardenID
left outer join leavetype c on src.leaveid = c.leaveid
WHERE src.KindergardenID = ' + CAST(#kindergardenid as varchar(max)) + '
GROUP BY src.EmployeeID, isnull(b.EmployeeName,'''') +'' ''+ isnull(b.LastName,''''), CheckinDate,LeaveDesc
) x
pivot
(
max(Result)
for CheckinDate in (' + #cols + ')
) p

How to merge two queries into one

How can I join these 2 SQL statements? I want the columns of the first and the columns of the second to appear together as one SQL query.
SELECT
E.tbl1_ORG AS Organización, E.tbl1_CODE AS [Orden de Trabajo],
E.tbl1_OBJECT AS Equipo, O.tbl3_POSITION AS Posicion,
E.tbl1_JOBTYPE AS [Tipo de Trabajo],
E.tbl1_DESC AS [Descripcion OT], E.tbl1_WORKADDRESS AS Comentarios,
E.tbl1_REQM AS Error, B.tbl2_PERSON AS Trabajador,
B.tbl2_ENTERED AS Fecha, B.tbl2_HOURS AS Horas
FROM
dbo.table1 AS E
INNER JOIN
dbo.table2 AS B ON E.tbl1_CODE = B.tbl2_EVENT
INNER JOIN
dbo.table3 AS O ON O.tbl3_CODE = E.tbl1_OBJECT
WHERE
E.tbl1_JOBTYPE IN ('PM', 'CM', 'PMM') and
E.tbl1_ORG = #PROMPT('Organización')# and
B.tbl2_ENTERED between #PROMPT('Fecha_Inicio')# and #PROMPT('Fecha_Final')# and
(E.tbl1_REQM = #PROMPT('Error')# OR #PROMPT('Error')# = '%') and
(E.tbl1_OBJECT = #PROMPT('Equipo')# OR #PROMPT('Equipo')# = '%') and
(O.tbl3_POSITION = #PROMPT('Posicion')# OR #PROMPT('Posicion')# = '%')
And:
SELECT
tbl2_event 'Orden de Trabajo',
STUFF((SELECT ', ' + CAST(tbl2_person AS VARCHAR(100)) [text()]
FROM table2
WHERE tbl2_event = t.tbl2_event
FOR XML PATH(''), TYPE).value('.','NVARCHAR(MAX)'),1,1,' ') Empleados,
STUFF((SELECT ', ' + CAST(tbl2_hours AS VARCHAR(100)) [text()]
FROM table2
WHERE tbl2_event = t.tbl2_event
FOR XML PATH(''), TYPE).value('.','NVARCHAR(MAX)'), 1, 1, ' ') Horas
FROM table2 t
GROUP BY tbl2_event
Both work perfectly on their own, but I don't know how to merge them.
Add ROW_NUMBER to each query and then FULL JOIN them together. You'll need to decide on the ordering of rows in each query.
WITH
CTE1
AS
(
SELECT
ROW_NUMBER() OVER (ORDER BY ...) AS rn,
E.tbl1_ORG AS Organización, E.tbl1_CODE AS [Orden de Trabajo],
E.tbl1_OBJECT AS Equipo, O.tbl3_POSITION AS Posicion,
E.tbl1_JOBTYPE AS [Tipo de Trabajo],
E.tbl1_DESC AS [Descripcion OT], E.tbl1_WORKADDRESS AS Comentarios,
E.tbl1_REQM AS Error, B.tbl2_PERSON AS Trabajador,
B.tbl2_ENTERED AS Fecha, B.tbl2_HOURS AS Horas
FROM
dbo.table1 AS E
INNER JOIN
dbo.table2 AS B ON E.tbl1_CODE = B.tbl2_EVENT
INNER JOIN
dbo.table3 AS O ON O.tbl3_CODE = E.tbl1_OBJECT
WHERE
E.tbl1_JOBTYPE IN ('PM', 'CM', 'PMM') and
E.tbl1_ORG = #PROMPT('Organización')# and
B.tbl2_ENTERED between #PROMPT('Fecha_Inicio')# and #PROMPT('Fecha_Final')# and
(E.tbl1_REQM = #PROMPT('Error')# OR #PROMPT('Error')# = '%') and
(E.tbl1_OBJECT = #PROMPT('Equipo')# OR #PROMPT('Equipo')# = '%') and
(O.tbl3_POSITION = #PROMPT('Posicion')# OR #PROMPT('Posicion')# = '%')
)
,CTE2
AS
(
SELECT
ROW_NUMBER() OVER (ORDER BY ...) AS rn,
tbl2_event 'Orden de Trabajo',
STUFF((SELECT ', ' + CAST(tbl2_person AS VARCHAR(100)) [text()]
FROM table2
WHERE tbl2_event = t.tbl2_event
FOR XML PATH(''), TYPE).value('.','NVARCHAR(MAX)'),1,1,' ') Empleados,
STUFF((SELECT ', ' + CAST(tbl2_hours AS VARCHAR(100)) [text()]
FROM table2
WHERE tbl2_event = t.tbl2_event
FOR XML PATH(''), TYPE).value('.','NVARCHAR(MAX)'), 1, 1, ' ') Horas
FROM table2 t
GROUP BY tbl2_event
)
SELECT ...
FROM
CTE1 FULL JOIN CTE2 ON CTE1.rn = CTE2.rn
ORDER BY ...
;
If you have more than 2-3 tables to join like this FULL JOIN would quickly become ugly and slow. Have a look at my answer for a similar question for alternative solution: best way to "glue" columns together

SQL merging cells

I have this tables:
T:
D:
What I am trying to do is to get for each s_id all it's symbols (DBSymbol) in one cell (merge cells).
I have found this tutorial, and here is my code:
select T.s_id,
(select '; ' + D.symbol
from D
where T.D_b_id = D.id
FOR XML PATH('')) [DBSymbol]
from T
but here is what I am getting:
What is wrong??
Try this -
SELECT t1.s_id,
STUFF(
(SELECT '; ' + symbol AS [text()]
FROM (
SELECT t.s_id,
d.symbol
FROM T
INNER JOIN D ON T.d_b_id = D.id
WHERE t.s_id = t1.s_id
) x
FOR XML PATH('')
), 1, 1, '')
FROM T t1
GROUP BY t1.s_id
Check it: SQL Fiddle
select DISTINCT T.s_id,
Stuff((SELECT DISTINCT '; ' + D.symbol
from D
--where T.D_b_id = D.id
FOR XML PATH('')),1,1,'') [DBSymbol]
from T
Example here

TSQL Removing last comma from concatenated string

I've a column with concatenated values, but the string comes with a comma at the end.
How can I remove the last comma on existing values?
SELECT
m.Mais_Id
, m.Outro
(SELECT CAST(emp.First_Name + ' ' + emp.Last_Name + ', ' AS VARCHAR(MAX))
FROM
Patos p
LEFT JOIN
Employee emp
ON
p.Pato_Id = emp.Pato_Id
WHERE
m.Pato_Id = p.Pato_Id
FOR XML PATH ('')
) AS Names
FROM
Mais m
I've this:
Mais_Id Outro Names
0 As Adn Meas, Fjds Poi, Csa Drop,
1 Be
2 Tee As Been,
This is the pretended result:
Mais_Id Outro Names
0 As Adn Meas, Fjds Poi, Csa Drop
1 Be
2 Tee As Been
Most neat way to do this is to use stuff() function:
stuff(
(
select ', ' + cast(emp.First_Name + ' ' + emp.Last_Name as varchar(max))
from Patos as p
left outer join Employee as emp on p.Pato_Id = emp.Pato_Id
where m.Pato_Id = p.Pato_Id
for xml path(''), type
).value('.', 'nvarchar(max)')
, 1, 2, '') as Names
Note it's also safer to get concatenated string with value() function, so if you have special characters like & or < it will be properly shown.
Try this:
SELECT Mais_id, m.Outro, Substring(newColumn, 0, LEN(newColumn) - 1)
FROM (
SELECT
m.Mais_Id
, m.Outro
(SELECT CAST(emp.First_Name + ' ' + emp.Last_Name + ', ' AS VARCHAR(MAX)) as newColumn
FROM
Patos p
LEFT JOIN
Employee emp
ON
p.Pato_Id = emp.Pato_Id
WHERE
m.Pato_Id = p.Pato_Id
FOR XML PATH ('')
) AS Names
FROM
Mais m
)