两列数据的所有可能组合
我有一个两列视图,
Product Id Tag
----------------------
1 Leather
1 Watch
2 Red
2 Necklace
2 Pearl
我试图获取产品的所有可能的标签组合,如下所示:
1 Leather
1 Leather,Watch
2 Pearl
2 Pearl,Necklace
2 Pearl Necklace,Red
2 Necklace
2 Necklace, Red
2 Red
我发现并窃取了一些 SQL,它们为我提供了所有版本(但不是小版本)的完整列表,如下所示。
任何想法,都开始让我头疼。虚拟品脱最佳答案。
SELECT ProductId,
(SELECT CAST(Tag + ', ' AS VARCHAR(MAX))
FROM ProductByTagView
WHERE Product.ProductId = ProductByTagView.ProductId
order by tag
FOR XML PATH ('')) AS Tags
FROM Product
I have a two column view
Product Id Tag
----------------------
1 Leather
1 Watch
2 Red
2 Necklace
2 Pearl
I'm trying to get all possible combinations of tags for a product as such:
1 Leather
1 Leather,Watch
2 Pearl
2 Pearl,Necklace
2 Pearl Necklace,Red
2 Necklace
2 Necklace, Red
2 Red
I've found and stolen some SQL that give me the complete list for all but not the small versions, its below.
Any ideas, it's started to make my head hurt. A virtual pint for the best answer.
SELECT ProductId,
(SELECT CAST(Tag + ', ' AS VARCHAR(MAX))
FROM ProductByTagView
WHERE Product.ProductId = ProductByTagView.ProductId
order by tag
FOR XML PATH ('')) AS Tags
FROM Product
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
这是一种方法。
理论上,每个产品最多可以处理 20 个标签(受数字表大小的限制),但我没有费心去尝试。在我的桌面上,大约需要 30 秒才能生成带有 16 个标签的单个产品的 65,535 个结果。希望每个产品的实际标签数量会比这个少很多!
退货
Here's one way.
In theory it can cope with up to 20 tags per Product (limited by the size of the numbers table) I didn't bother attempting that though. On my desktop it took about 30 seconds to churn out the 65,535 results for a single product with 16 tags. Hopefully your actual number of tags per product will be a lot less than that!
Returns
像这样的东西?:
Something like this?:
我的预设答案:
假设您有一个包含整数的辅助数字表。
My canned answer:
Suppose you have a auxiliary Numbers table with integer numbers.
正如 @Andomar 所建议的那样,这是一个最好用客户端语言解决的问题,我尝试了各种解决方案(谢谢大家),尽管那里似乎有一些东西,特别是在马丁的回答中,问题是运行查询所需的时间。
再次感谢你们。
亚历克
As @Andomar suggested this turned out to be a problem best solved in a client language, I tried the various solutions (thanks guys) and although there seemed to be something there, especially in Martin's answer the problem was the time taken to run the query.
Thanks again guys.
Alec