【发布时间】:2018-07-15 20:27:30
【问题描述】:
这是我的表格示例:
项目
+----------+---------------+
| txt_item | txt_unique_id |
+----------+---------------+
| Circle | 1 |
| Square | 2 |
| Triangle | 3 |
+----------+---------------+
tag_master
+---------+----------+
| txt_tag | opt_type |
+---------+----------+
| red | color |
| blue | color |
| yellow | color |
| large | size |
| medium | size |
| small | size |
+---------+----------+
item_tags
+---------+---------------+
| txt_tag | txt_unique_id |
+---------+---------------+
| red | 1 |
| blue | 1 |
| large | 1 |
| small | 1 |
| red | 2 |
| yellow | 2 |
| small | 2 |
| medium | 2 |
| red | 3 |
| yellow | 3 |
+---------+---------------+
我想退货:
+----------+----------------------------+
| Circle | red, blue, large, small |
| Square | red, yellow, small, medium |
| Triangle | red, yellow |
+----------+----------------------------+
这就是我得到的:
+----------+---------------------------------------------+
| Circle | red, red, red, blue, large, small, small |
| Square | red, red, red, yellow, yellow, small, small |
| Triangle | red, red, red, yellow, yellow |
+----------+---------------------------------------------+
这是我现在的位置:
CREATE TABLE #screening_tags
(
txt_unique_id VARCHAR(36),
tags VARCHAR(1000)
)
INSERT INTO #screening_tags
(txt_unique_id,
tags)
(SELECT txt_unique_id,
( STUFF((SELECT ' , ' + t.txt_tag
FROM item_tags t
JOIN tag_master_ tm
ON t.txt_tag = tm.txt_tag
JOIN items i
ON t.txt_unique_id = i.txt_unique_id
ORDER BY opt_type,
txt_tage
FOR xml path('')), 1, 1, '') )
FROM item_tags t)
SELECT *
FROM #screening_tags
我也尝试过使用 COALESCE,但我遗漏了一些东西。我需要一个 DISTINCT 或其他东西,但我尝试过的一切都不起作用。如果我想按 opt_type 排序,我不能使用 DISTINCT 或 TOP 1。感谢帮助。
【问题讨论】: