Try this...
DECLARE @temp TABLE
(
keyword VARCHAR(max),
times INT
)
INSERT INTO @temp
VALUES ('open windows',
1000 ),
('closed windows',
750 ),
('open doors',
350 ),
('closed doors',
250 ),
('nice window',
100 ),
('nice windows',
50 ),
('ugly doors',
25 )
DECLARE @allValues VARCHAR(max) = (SELECT Stuff((SELECT
',' + Replace(p2.keyword, ' ',
',')
FROM @temp p2
ORDER BY p2.keyword
FOR xml path(''), type).value('.', 'varchar(max)'), 1, 1, ''))
-- find distinct words
SELECT DISTINCT t.element,
(SELECT Sum(k.times)
FROM @temp k
WHERE k.keyword LIKE '%' + t.element + '%')
FROM dbo.Func_split(@allValues, ',') t
The function Func_split
(credit: https://stackoverflow.com/a/21428746/710925)
CREATE FUNCTION [dbo].[func_Split]
(
@DelimitedString varchar(8000),
@Delimiter varchar(100)
)
RETURNS @tblArray TABLE
(
ElementID int IDENTITY(1,1), -- Array index
Element varchar(1000) -- Array element contents
)
AS
BEGIN
-- Local Variable Declarations
-- ---------------------------
DECLARE @Index smallint,
@Start smallint,
@DelSize smallint
SET @DelSize = LEN(@Delimiter)
-- Loop through source string and add elements to destination table array
-- ----------------------------------------------------------------------
WHILE LEN(@DelimitedString) > 0
BEGIN
SET @Index = CHARINDEX(@Delimiter, @DelimitedString)
IF @Index = 0
BEGIN
INSERT INTO
@tblArray
(Element)
VALUES
(LTRIM(RTRIM(@DelimitedString)))
BREAK
END
ELSE
BEGIN
INSERT INTO
@tblArray
(Element)
VALUES
(LTRIM(RTRIM(SUBSTRING(@DelimitedString, 1,@Index - 1))))
SET @Start = @Index + @DelSize
SET @DelimitedString = SUBSTRING(@DelimitedString, @Start , LEN(@DelimitedString) - @Start + 1)
END
END
RETURN
END