给出下表:
**Title** | **Value**
Color | Red
Color | Green
Color | Blue
Size | Small
Size | Medium
Size | Large
现在我想制作与颜色和尺寸相关的所有可能组合。
输出应如下所示:
**Size** | **Color**
Small | Red
Small | Green
Small | Blue
Medium | Red
Medium | Green
Medium | Blue
Large | Red
Large | Green
Large | Blue
那么,有9种可能的颜色和大小属性的组合(变体)
如何在SQL Server数据库中实现这一目标
答案 0 :(得分:0)
您可以使用cross join
:
select s.size, c.color
from (select value as size from t where title = 'size') s cross join
(select value as color from t where title = 'color') c;
实际上,您不需要子查询:
select ts.value as size, tc.value as color
from t ts cross join
t tc
where ts.title = 'size' and tc.title = 'color';
答案 1 :(得分:0)
您可以对表进行交叉自联接,将一侧限制为仅颜色记录,将另一侧限制为仅大小记录。
SELECT
t2.Value,
t1.Value
FROM yourTable t1
CROSS JOIN yourTable t2
WHERE
t1.Title = 'Color' AND
t2.Title = 'Size'
ORDER BY
CASE WHEN t2.Value = 'Small' THEN 1
WHEN t2.Value = 'Medium' THEN 2
WHEN t2.Value = 'Large' THEN 3 END,
CASE WHEN t1.Value = 'Red' THEN 1
WHEN t1.Value = 'Green' THEN 2
WHEN t1.Value = 'Blue' THEN 3 END;
请注意,如果您不需要按照向我们展示的顺序显示数据,则可以省略冗长的ORDER BY
子句。例如,如果您有一个使用此数据的应用程序或表示层,那么对它进行排序可能无关紧要或不必要。
<强>输出:强>
在这里演示: