Click here to monitor SSC
SQLServerCentral is supported by Red Gate Software Ltd.
 
Log in  ::  Register  ::  Not logged in
 
 
 
        
Home       Members    Calendar    Who's On


Add to briefcase ««123»»

Generating a Distinct Delimited List Using XML Expand / Collapse
Author
Message
Posted Tuesday, June 29, 2010 10:32 AM
SSCrazy

SSCrazySSCrazySSCrazySSCrazySSCrazySSCrazySSCrazySSCrazy

Group: General Forum Members
Last Login: Friday, September 5, 2014 2:00 PM
Points: 2,160, Visits: 2,191
This is a good article thanks!

I was going to mention that using GROUP BY instead of DISTINCT/ROW_NUMBER might be a good way to solve this, but I see someone has already suggested that. IMO DISTINCT should hardly ever be used, as it usually isn't the best option, like in this case it prevents you from being able to order the results by what you want.
Post #944819
Posted Tuesday, June 29, 2010 2:03 PM
SSC-Addicted

SSC-AddictedSSC-AddictedSSC-AddictedSSC-AddictedSSC-AddictedSSC-AddictedSSC-AddictedSSC-Addicted

Group: General Forum Members
Last Login: Today @ 7:10 AM
Points: 412, Visits: 1,411
Hi Brian, why would you want to eliminate row_number() from the query? Simply copy and paste your code into the test script that SwePeso posted and see for yourself how your version compares to the alternatives already presented. Peso's suggestion has by far the least IO and cpu time; I've taken that and added a fix for a functional problem in all suggestions: the special-characters &, < and > that for xml translates into & amp ;, & lt ; and & gt ; respectively (I put some additional spaces in that aren't in the real codes because the forum software shows the complete codes as &, < and > again). Your example re-introduces that problem and performs much worse because it re-introduces distinct instead of the group by in a sub query. So is there any specific reason why you think your version should be used instead of mine?

edit: codes were not shown correctly by the forum software.




Posting Data Etiquette - Jeff Moden
Posting Performance Based Questions - Gail Shaw
Hidden RBAR - Jeff Moden
Cross Tabs and Pivots - Jeff Moden
Catch-all queries - Gail Shaw


If you don't have time to do it right, when will you have time to do it over?
Post #945017
Posted Tuesday, June 29, 2010 2:48 PM
SSC-Enthusiastic

SSC-EnthusiasticSSC-EnthusiasticSSC-EnthusiasticSSC-EnthusiasticSSC-EnthusiasticSSC-EnthusiasticSSC-EnthusiasticSSC-Enthusiastic

Group: General Forum Members
Last Login: Friday, October 3, 2014 7:54 AM
Points: 116, Visits: 99
OK, then use GROUP:

--An alternative without ROW_NUMBER()
--How about this?
select
u.UserID
, stuff((
select ', ' + u2.RoleName
from @UserRole u2
where u2.UserID = u.UserID
and u2.RoleAssignedDate = (
select min(u3.RoleAssignedDate)
from @UserRole u3
where u3.UserID = u2.UserID
and u3.RoleName = u2.RoleName
)
order by u2.RoleAssignedDate asc
for xml path('')
), 1, 2, '') 'RoleName'
from @UserRole u
group by u.UserID

*** R.P.Rozema *****************************************************************

SQL Server Execution Times:
CPU time = 0 ms, elapsed time = 1 ms.
Table '#4F1BAE10'. Scan count 8, logical reads 8, physical reads 0, read-ahead reads 0, lob logical reads 0, lob physical reads 0, lob read-ahead reads 0.

SQL Server Execution Times:
CPU time = 0 ms, elapsed time = 4 ms.
*** Brian Barkauskas ***********************************************************

SQL Server Execution Times:
CPU time = 0 ms, elapsed time = 1 ms.
Table '#4F1BAE10'. Scan count 8, logical reads 8, physical reads 0, read-ahead reads 0, lob logical reads 0, lob physical reads 0, lob read-ahead reads 0.

SQL Server Execution Times:
CPU time = 0 ms, elapsed time = 2 ms.
Post #945035
Posted Tuesday, June 29, 2010 3:10 PM
SSC-Enthusiastic

SSC-EnthusiasticSSC-EnthusiasticSSC-EnthusiasticSSC-EnthusiasticSSC-EnthusiasticSSC-EnthusiasticSSC-EnthusiasticSSC-Enthusiastic

Group: General Forum Members
Last Login: Friday, October 3, 2014 7:54 AM
Points: 116, Visits: 99
Actually for readability, this one's even better,
It has only 32 "words" compared to your 70,
182 non-space characters to your 363,
and runs just as fast:

select
u.UserID
, stuff((
select ', ' + u2.RoleName
from @UserRole u2
where u2.UserID = u.UserID
group by u2.RoleName
order by min(u2.RoleAssignedDate)
for xml path('')
),1,2,'') 'RoleName'
from @UserRole u
group by u.UserID

Post #945059
Posted Tuesday, June 29, 2010 5:21 PM


SSC-Dedicated

SSC-DedicatedSSC-DedicatedSSC-DedicatedSSC-DedicatedSSC-DedicatedSSC-DedicatedSSC-DedicatedSSC-DedicatedSSC-DedicatedSSC-DedicatedSSC-DedicatedSSC-DedicatedSSC-Dedicated

Group: General Forum Members
Last Login: Today @ 10:15 PM
Points: 35,399, Visits: 31,959
Brian Barkauskas (6/29/2010)
OK, then use GROUP:

--An alternative without ROW_NUMBER()
--How about this?
select
u.UserID
, stuff((
select ', ' + u2.RoleName
from @UserRole u2
where u2.UserID = u.UserID
and u2.RoleAssignedDate = (
select min(u3.RoleAssignedDate)
from @UserRole u3
where u3.UserID = u2.UserID
and u3.RoleName = u2.RoleName
)
order by u2.RoleAssignedDate asc
for xml path('')
), 1, 2, '') 'RoleName'
from @UserRole u
group by u.UserID

*** R.P.Rozema *****************************************************************

SQL Server Execution Times:
CPU time = 0 ms, elapsed time = 1 ms.
Table '#4F1BAE10'. Scan count 8, logical reads 8, physical reads 0, read-ahead reads 0, lob logical reads 0, lob physical reads 0, lob read-ahead reads 0.

SQL Server Execution Times:
CPU time = 0 ms, elapsed time = 4 ms.
*** Brian Barkauskas ***********************************************************

SQL Server Execution Times:
CPU time = 0 ms, elapsed time = 1 ms.
Table '#4F1BAE10'. Scan count 8, logical reads 8, physical reads 0, read-ahead reads 0, lob logical reads 0, lob physical reads 0, lob read-ahead reads 0.

SQL Server Execution Times:
CPU time = 0 ms, elapsed time = 2 ms.


You good folks simply aren't using enough data to claim victory in any of the cases.


--Jeff Moden
"RBAR is pronounced "ree-bar" and is a "Modenism" for "Row-By-Agonizing-Row".

First step towards the paradigm shift of writing Set Based code:
Stop thinking about what you want to do to a row... think, instead, of what you want to do to a column."

(play on words) "Just because you CAN do something in T-SQL, doesn't mean you SHOULDN'T." --22 Aug 2013

Helpful Links:
How to post code problems
How to post performance problems
Post #945114
Posted Tuesday, June 29, 2010 9:10 PM


Ten Centuries

Ten CenturiesTen CenturiesTen CenturiesTen CenturiesTen CenturiesTen CenturiesTen CenturiesTen Centuries

Group: General Forum Members
Last Login: Wednesday, September 24, 2014 1:20 PM
Points: 1,276, Visits: 1,135
How's this for data? :)

CREATE TABLE #Role
(
RoleName VARCHAR(100)
);
GO

INSERT INTO #Role
(
RoleName
)
VALUES ('Accounting'), ('Approver'), ('Developer'), ('International Sales Manager'), ('Marketing'), ('System Administrator'),
('Technical Customer'), ('Technical Director'), ('Training');
GO

CREATE TABLE #UserRole
(
UserID INT NOT NULL,
RoleName VARCHAR(100) NOT NULL,
ProjectID INT NOT NULL,
RoleAssignedDate DATETIME NOT NULL,
PRIMARY KEY
(
UserID,
RoleName,
ProjectID,
RoleAssignedDate
)
);
GO

CREATE TABLE #Numbers
(
Num INT NOT NULL PRIMARY KEY
);
GO

WITH DIGITS
AS
(
SELECT 0 AS Num
UNION ALL
SELECT Num + 1
FROM DIGITS
WHERE Num < 10
)
INSERT INTO #Numbers
(
Num
)
SELECT Num
FROM DIGITS;
GO

WITH NUMBERS
AS
(
SELECT HundredThousand.Num * 100000 + TenThousand.Num * 10000 +
Thousand.Num * 1000 + Hundred.Num * 100 +
Ten.Num + One.Num AS Num
FROM #Numbers HundredThousand
CROSS JOIN #Numbers TenThousand
CROSS JOIN #Numbers Thousand
CROSS JOIN #Numbers Hundred
CROSS JOIN #Numbers Ten
CROSS JOIN #Numbers One
),
RANDOMDATA
AS
(
SELECT Num AS UserID,
RoleName,
ABS(CHECKSUM(NEWID()) % 8000) + 1000 AS ProjectID,
DATEADD(DAY, -ABS(CHECKSUM(NEWID()) % 1000), GETDATE()) AS RoleAssignedDate,
NEWID() AS SortOrder
FROM NUMBERS
CROSS JOIN #Role
)
INSERT INTO #UserRole
(
UserID,
RoleName,
ProjectID,
RoleAssignedDate
)
SELECT TOP(1000000) UserID,
RoleName,
ProjectID,
RoleAssignedDate
FROM RANDOMDATA
ORDER BY SortOrder;
GO

Post #945170
Posted Wednesday, June 30, 2010 2:20 AM
SSC Eights!

SSC Eights!SSC Eights!SSC Eights!SSC Eights!SSC Eights!SSC Eights!SSC Eights!SSC Eights!

Group: General Forum Members
Last Login: Today @ 7:29 AM
Points: 895, Visits: 2,443
I did something similar the other month to demonstrate the use of XML data, and how to remove the dreaded cursors from the code, granted it was written on an intitally small set and there was not requirement for Ordering the data in the output list.

The main difference was that I prefixed the list with a Comma, this mean that I could simply do a substring(XMLString,2,4000), the code looked like this

Select Distinct
EmployeeID
,Substring(Replace
(Replace((Select ','+SkillData
From #tmp
where EmployeeID=a.EmployeeID
FOR XML RAW),'<Row Data="',''),'"/>',''),2,4000) Data
from #tmp a

The XML data before the Replace is run looked like

<row Data=",UU"/><row Data=",WW"/><row Data=",XX"/><row Data=",ZZ"/>

After the replace you had a string that looked like this ",UU,WW,XX,ZZ"

The downside is the distinct has on large data sets it could have an impact.

Having said that I do like the look of some of the pure T-SQL scripts.


_________________________________________________________________________
SSC Guide to Posting and Best Practices
Post #945289
Posted Wednesday, June 30, 2010 4:39 AM
SSC-Addicted

SSC-AddictedSSC-AddictedSSC-AddictedSSC-AddictedSSC-AddictedSSC-AddictedSSC-AddictedSSC-Addicted

Group: General Forum Members
Last Login: Today @ 7:10 AM
Points: 412, Visits: 1,411
I did the test and combined Mike's test data with (most of) the suggestions:

*** Peso ***********************************************************************
SQL Server Execution Times:
CPU time = 0 ms, elapsed time = 0 ms.
UserID Roles
----------- -------------------------------------------------------------------------------------------------------------------------------------
1 Technical Director,Technical Customer
2 R&D,Approver
4 International Sales Manager,Marketing,System Administrator,Technical Customer

...

1111018 International Sales Manager,Technical Director
1111019 Approver,Marketing
1111020 Approver

(210092 row(s) affected)

Table '#UserRole___________________________________________________________________________________________________________0000000007DC'. Scan count 210093, logical reads 641750, physical reads 0, read-ahead reads 0, lob logical reads 0, lob physical reads 0, lob read-ahead reads 0.

SQL Server Execution Times:
CPU time = 7719 ms, elapsed time = 7917 ms.


*** Puja Shah ******************************************************************
SQL Server Execution Times:
CPU time = 0 ms, elapsed time = 0 ms.
UserID Roles
----------- -------------------------------------------------------------------------------------------------------------------------------------
1 Technical Director, Technical Customer
2 R&D, Approver
4 International Sales Manager, Marketing, System Administrator, Technical Customer

...

1111018 International Sales Manager, Technical Director
1111019 Approver, Marketing
1111020 Approver

(210092 row(s) affected)

Table '#UserRole___________________________________________________________________________________________________________0000000007DC'. Scan count 210095, logical reads 641749, physical reads 0, read-ahead reads 0, lob logical reads 0, lob physical reads 0, lob read-ahead reads 0.
Table 'Worktable'. Scan count 1210296, logical reads 3993980, physical reads 0, read-ahead reads 0, lob logical reads 0, lob physical reads 0, lob read-ahead reads 0.

SQL Server Execution Times:
CPU time = 1509437 ms, elapsed time = 772965 ms.


*** Kailash Mishra *************************************************************
SQL Server Execution Times:
CPU time = 0 ms, elapsed time = 0 ms.
UserID
----------- -------------------------------------------------------------------------------------------------------------------------------------
1 Technical Customer,Technical Director
2 Approver,R&D
4 International Sales Manager,Marketing,System Administrator,Technical Customer

...

1111018 International Sales Manager,Technical Director
1111019 Approver,Marketing
1111020 Approver

(210092 row(s) affected)

Table '#UserRole___________________________________________________________________________________________________________0000000007DC'. Scan count 210095, logical reads 641749, physical reads 0, read-ahead reads 0, lob logical reads 0, lob physical reads 0, lob read-ahead reads 0.
Table 'Worktable'. Scan count 1210312, logical reads 4167863, physical reads 0, read-ahead reads 0, lob logical reads 0, lob physical reads 0, lob read-ahead reads 0.

SQL Server Execution Times:
CPU time = 103482 ms, elapsed time = 54131 ms.


*** R.P.Rozema ****************************************************************
SQL Server parse and compile time: 
CPU time = 0 ms, elapsed time = 13 ms.

SQL Server Execution Times:
CPU time = 0 ms, elapsed time = 0 ms.
UserID Roles
----------- -------------------------------------------------------------------------------------------------------------------------------------
1 Technical Director, Technical Customer
2 R&D, Approver
4 International Sales Manager, Marketing, System Administrator, Technical Customer

...

1111018 International Sales Manager, Technical Director
1111019 Approver, Marketing
1111020 Approver

(210092 row(s) affected)

Table '#UserRole___________________________________________________________________________________________________________0000000007DC'. Scan count 210093, logical reads 641750, physical reads 0, read-ahead reads 0, lob logical reads 0, lob physical reads 0, lob read-ahead reads 0.

SQL Server Execution Times:
CPU time = 20672 ms, elapsed time = 21298 ms.


*** Brian Barkauskas 1st ****************************************************************
SQL Server Execution Times:
CPU time = 0 ms, elapsed time = 0 ms.
UserID RoleName
----------- -------------------------------------------------------------------------------------------------------------------------------------
8 Marketing, Technical Director, Training, Accounting, Approver
9 Accounting, R&D, Developer
10 Accounting, R&D, Technical Customer, System Administrator, Training

...

1111014 Approver, Technical Director, Training, System Administrator
1111015 Developer, Training
1111016 Marketing, R&D

(210092 row(s) affected)

Table '#UserRole___________________________________________________________________________________________________________0000000007DC'. Scan count 974634, logical reads 2944527, physical reads 0, read-ahead reads 0, lob logical reads 0, lob physical reads 0, lob read-ahead reads 0.
Table 'Worktable'. Scan count 1210315, logical reads 4196120, physical reads 0, read-ahead reads 0, lob logical reads 0, lob physical reads 0, lob read-ahead reads 0.

SQL Server Execution Times:
CPU time = 96921 ms, elapsed time = 51262 ms.


*** Brian Barkauskas 2nd ****************************************************************
SQL Server Execution Times:
CPU time = 0 ms, elapsed time = 0 ms.
UserID RoleName
----------- -------------------------------------------------------------------------------------------------------------------------------------
1 Technical Director, Technical Customer
2 R&D, Approver
4 International Sales Manager, Marketing, System Administrator, Technical Customer

...

1111018 International Sales Manager, Technical Director
1111019 Approver, Marketing
1111020 Approver

(210092 row(s) affected)

Table '#UserRole___________________________________________________________________________________________________________0000000007DC'. Scan count 210093, logical reads 641750, physical reads 0, read-ahead reads 0, lob logical reads 0, lob physical reads 0, lob read-ahead reads 0.

SQL Server Execution Times:
CPU time = 8000 ms, elapsed time = 8233 ms.


Soooooooo... Granted, Brian's 2nd is faster than my suggestion. However, that 2nd suggestion is nearly identical to Peso's suggestion, so you can hardly claim credit for that.

Plus, as you can not see due to the forum code translating the & amp ; in the output back into &, I've added 'R&D' as a role. Mine is the only suggestion that correctly returns 'R&D' instead of 'R& amp ;D' (without the spaces).

To see what the difference is I also tried changing the case row_number() when 1 then '' else ',' end construct into the stuff( ..., 1, 2, '')-construction in my suggestion and found out that the stuff construction is indeed faster: about 0.013ms per row. Resulting in a gain of roughly 3 seconds for these 200K rows. So it is better to use stuff() on the result to replace the first ',' in the resulting string than to use case row_number to suppress the ',' on only the first role name.


In conclusion: When you can guarantee the role name will never contain any of &, < or >, use this:
-- Peso
PRINT '*** Peso ***********************************************************************'

SELECT b.UserID,
STUFF(f.Roles, 1, 1, '') AS Roles
FROM (
SELECT UserID
FROM #UserRole
GROUP BY UserID
) AS b
CROSS APPLY (
SELECT TOP(100) PERCENT
',' + w.RoleName
FROM #UserRole AS w
WHERE w.UserID = b.UserID
GROUP BY w.RoleName
ORDER BY MIN(RoleAssignedDate)
FOR XML PATH('')
) AS f(Roles)
ORDER BY b.UserID

If however your role name can contain any of the characters &, < or >, use this -at the cost of almost doubling the required cpu time from 8250 ms to 17203 ms for these 210092 rows- :
PRINT '*** Peso & R.P.Rozema ****************************************************************'

SELECT b.UserID,
STUFF(f.Roles.value('.','nvarchar(max)'), 1, 1, '') AS Roles
FROM (
SELECT UserID
FROM #UserRole
GROUP BY UserID
) AS b
CROSS APPLY (
SELECT ',' + w.RoleName as [text()]
FROM #UserRole AS w
WHERE w.UserID = b.UserID
GROUP BY w.RoleName
ORDER BY MIN(RoleAssignedDate)
FOR XML PATH(''), type
) AS f(Roles)
ORDER BY b.UserID

Or cheat and do the translation of the xml escaped characters yourself too, reducing the loss of performance a little to 13985 ms cpu time on the same data set:
PRINT '*** Peso & R.P.Rozema ****************************************************************'

SELECT b.UserID,
replace(replace(replace(STUFF(f.Roles, 1, 1, ''), '&', '&'), '<', '<'), '>', '>') AS Roles
FROM (
SELECT UserID
FROM #UserRole
GROUP BY UserID
) AS b
CROSS APPLY (
SELECT ',' + w.RoleName as [text()]
FROM #UserRole AS w
WHERE w.UserID = b.UserID
GROUP BY w.RoleName
ORDER BY MIN(RoleAssignedDate)
FOR XML PATH('')
) AS f(Roles)
ORDER BY b.UserID





Posting Data Etiquette - Jeff Moden
Posting Performance Based Questions - Gail Shaw
Hidden RBAR - Jeff Moden
Cross Tabs and Pivots - Jeff Moden
Catch-all queries - Gail Shaw


If you don't have time to do it right, when will you have time to do it over?
Post #945348
Posted Wednesday, June 30, 2010 5:57 AM


Ten Centuries

Ten CenturiesTen CenturiesTen CenturiesTen CenturiesTen CenturiesTen CenturiesTen CenturiesTen Centuries

Group: General Forum Members
Last Login: Wednesday, September 24, 2014 1:20 PM
Points: 1,276, Visits: 1,135
I didn't get a chance to run any tests against the data (it was a little late when I posted that), but one thing worth considering is whether or not a specific indexing strategy/index changes can improve the results. I slapped a clustered PK on the sample data, but not necessarily the most efficient for any given query.

Thanks
Mike C
Post #945384
Posted Wednesday, June 30, 2010 6:36 AM
Forum Newbie

Forum NewbieForum NewbieForum NewbieForum NewbieForum NewbieForum NewbieForum NewbieForum Newbie

Group: General Forum Members
Last Login: Wednesday, December 4, 2013 12:41 PM
Points: 5, Visits: 13
I found Brian's 2nd solution easier to understand....I dig the STUFF...never used that before.
Post #945419
« Prev Topic | Next Topic »

Add to briefcase ««123»»

Permissions Expand / Collapse