Friday, August 29, 2014

Group By partial string

Give this concept a try:



DECLARE @forumTable TABLE (names VARCHAR(100))
INSERT INTO @forumTable (names)
VALUES
('Joe'),
('John;Robert;Doug'),
('Barry;Robert'),
('Doug'),
('Robert;Doug;Joe;John')
DECLARE @loopTable TABLE (names VARCHAR(100))
INSERT INTO @loopTable (names)
SELECT * FROM @forumTable

DECLARE @thisName VARCHAR(100)
DECLARE @names TABLE (name VARCHAR(100))
WHILE (SELECT COUNT(*) FROM @loopTable) > 0
BEGIN
SET @thisName = (SELECT TOP 1 names FROM @loopTable)
WHILE CHARINDEX(';', @thisName) > 0
BEGIN
IF NOT EXISTS (SELECT 'x' FROM @names WHERE name = LEFT(@thisName,CHARINDEX(';',@thisName)-1))
BEGIN
INSERT INTO @names (name) VALUES (LEFT(@thisName,CHARINDEX(';',@thisName)-1))
END
SET @thisName = RIGHT(@thisName,LEN(@thisName)-CHARINDEX(';',@thisName))
END
IF NOT EXISTS (SELECT 'x' FROM @names WHERE name = @thisName)
BEGIN
INSERT INTO @names (name) VALUES (@thisName)
END
DELETE FROM @loopTable WHERE names = (SELECT TOP 1 names FROM @loopTable)
END

SELECT name, COUNT(*)
FROM @names
INNER JOIN @forumTable
ON names LIKE '%'+name+'%'
GROUP BY name



You can, of course, use temp tables, or actual tables if you'd prefer. It's much easier to test (for me at least) using table variables.

No comments:

Post a Comment