Это динамический сводный запрос. Поэтому я бы порекомендовал это, только если ваши атрибуты FoodAttributeTable
являются динамическими.
Создание таблиц и вставка данных
CREATE TABLE FoodAttributeTable(
Food nvarchar(50) NULL,
AttributeName nvarchar(50) NULL,
AttributeValue nvarchar(50) NULL
)
INSERT FoodAttributeTable (Food, AttributeName, AttributeValue) VALUES (N'Strawberry', N'Vitamin', N'C')
INSERT FoodAttributeTable (Food, AttributeName, AttributeValue) VALUES (N'Strawberry', N'Weight', N'15g')
INSERT FoodAttributeTable (Food, AttributeName, AttributeValue) VALUES (N'Strawberry', N'Color', N'Red')
INSERT FoodAttributeTable (Food, AttributeName, AttributeValue) VALUES (N'Broccoli', N'Vitamin', N'B')
INSERT FoodAttributeTable (Food, AttributeName, AttributeValue) VALUES (N'Broccoli', N'Weight', N'70g')
INSERT FoodAttributeTable (Food, AttributeName, AttributeValue) VALUES (N'Broccoli', N'Color', N'Green')
CREATE TABLE FoodTable(
Food nvarchar(50) NULL,
Price decimal(18, 0) NULL
)
INSERT FoodTable (Food, Price) VALUES (N'Strawberry', N'10')
INSERT FoodTable (Food, Price) VALUES (N'Broccoli', N'25')
Запрос
DECLARE @colsValues AS NVARCHAR(max) = Stuff((SELECT DISTINCT ',' + Quotename(fat.attributename)
FROM foodattributetable fat
FOR xml path(''), type).value('.', 'NVARCHAR(MAX)'), 1, 1, '');
DECLARE @query AS NVARCHAR(max) = 'SELECT *
FROM (SELECT *
FROM foodattributetable
PIVOT(Max(attributevalue)
FOR attributename IN ('+ @colsValues +')) piv) fat
INNER JOIN foodtable tb
ON tb.food = fat.food';
EXECUTE(@query)
выход
+------------+-------+---------+--------+------------+-------+
| Food | Color | Vitamin | Weight | Food | Price |
+------------+-------+---------+--------+------------+-------+
| Broccoli | Green | B | 70g | Broccoli | 25 |
| Strawberry | Red | C | 15g | Strawberry | 10 |
+------------+-------+---------+--------+------------+-------+
Демо: http://rextester.com/ATZF46215