您需要对每个产品(品牌)的颜色进行拆分和计数:
SELECT products, colors
FROM (
SELECT
*,
DENSE_RANK() OVER (ORDER BY (
SELECT COUNT(DISTINCT LTRIM(RTRIM([value])))
FROM STRING_SPLIT(SUBSTRING(colors, 2, LEN(colors) - 2), ',')
) DESC
) AS rank
-- FROM YourTable
FROM (VALUES
('adidas', '{red, blue, black}'),
('puma', '{red, green, blue, orange}'),
('nike', '{red, green}')
) product (products, colors)
) t
WHERE rank <= 2
结果:
products colors
----------------------------------
puma {red, green, blue, orange}
adidas {red, blue, black}
如果您需要计算颜色,只需添加一列:
SELECT products, colors
FROM (
SELECT
*,
(
SELECT COUNT(DISTINCT LTRIM(RTRIM([value])))
FROM STRING_SPLIT(SUBSTRING(colors, 2, LEN(colors) - 2), ',')
) AS [count]
FROM (VALUES
('adidas', '{red, blue, black, blue, red}'),
('puma', '{red, green, blue}'),
('nike', '{red, green}')
) product (products, colors)
) t
WHERE [count] > 2