Разделить столбцы из одной таблицы и объединить их в несколько столбцов в другой - PullRequest
0 голосов
/ 01 мая 2018

Я хочу разбить столбец в одной таблице на несколько столбцов в другой таблице

Допустим, я хочу присоединить таблицу FoodAttributeTable к FoodTable:

FoodTable

+------------+-------+
|    Food    | Price |
+------------+-------+
| Strawberry |    10 |
| Broccoli   |    25 |
+------------+-------+

FoodAttributeTable

+------------+---------------+----------------+
|    Food    | AttributeName | AttributeValue |
+------------+---------------+----------------+
| Strawberry | Vitamin       | C              |
| Strawberry | Weight        | 15g            |
| Strawberry | Color         | Red            |
| Broccoli   | Vitamin       | B              |
| Broccoli   | Weight        | 70g            |
| Broccoli   | Color         | Green          |
+------------+---------------+----------------+

Таблица будет:

FoodTable

+------------+-------+---------+--------+-------+
|    Food    | Price | Vitamin | Weight | Color |
+------------+-------+---------+--------+-------+
| Strawberry |    10 | C       | 15g    | Red   |
| Broccoli   |    25 | B       | 70g    | Green |
+------------+-------+---------+--------+-------+

Ответы [ 2 ]

0 голосов
/ 01 мая 2018

Это динамический сводный запрос. Поэтому я бы порекомендовал это, только если ваши атрибуты 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

0 голосов
/ 01 мая 2018

вы можете использовать простой запрос PIVOT, как показано ниже. Ознакомьтесь с официальной MSDN документацией по PIVOT .

select 
Food,Price,Vitamin,Weight,Color
from
(
    select f.Food,f.Price,
     AttributeName  ,AttributeValue
    from
    FoodTable f join
    FoodAttributeTable fat on
    f.Food=fat.Food
)s
pivot
(max(AttributeValue) for AttributeName in (Vitamin,Weight,Color))
p

Также вот живое демо

...