问题描述
数据是平面归一化表:
|ID | Product selected | Product Code 1 | Product Code 2 | Product Code 3 | Cost of Product 1 | Cost of Product 2 | Cost of Product 3 | Rate of Product 1 | Rate of Product 2 | Rate of Product 3 |
|--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
|1 | ABCDEDFHIJKL | AAABBBCCCDDD | ABCDEDFHIJKL | DDDCCCBBBAAA | 995 | 495 | 0 | 4.4 | 6.3 | 7.8 |
|2 | DDDCCCBBBAAA | AAABBBCCCDDD | ABCDEDFHIJKL | DDDCCCBBBAAA | 995 | 495 | 0 | 4.4 | 6.3 | 7.8 |
内容:
使用所选产品(ABCDEDFHIJKL),在各行中查找以找到包含与所选产品相关的数据的列的相应位置。
所需的输出:
| Product selected | Cost of Product | Rate of Product |
--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
| ABCDEDFHIJKL | 495 | 6.3 |
| DDDCCCBBBAAA | 0 | 7.8 |
在R中做到这一点很简单,而且我敢肯定,对于一个比我更懂SQL的人,这将很容易
解决方法
您可以使用cross apply
:
select t.product_selected,x.cost_of_product,x.rate_of_product
from mytable t
cross apply (values
(product_code_1,cost_of_product_1,rate_of_product_1),(product_code_2,cost_of_product_2,rate_of_product_2),(product_code_3,cost_of_product_3,rate_of_product_3)
) as x(product_selected,cost_of_product,rate_of_product)
where x.product_selected = t.product_selected
,
使用unpivot,union或crossapply
取消样本
SELECT [Product selected],ProductCode,ProductCost,ProductRate
FROM
(
SELECT *
FROM dbo.table
) AS cp
UNPIVOT
(
ProductCode FOR PC IN ([Product Code 1],[Product Code 2],[Product Code 3])
) AS up
UNPIVOT
(
ProductCost FOR Po IN ([Cost of Product 1],[Cost of Product 2],[Cost of Product 3])
) AS up2
UNPIVOT
(
ProductRate FOR Pr IN ([Rate of Product 1],[Rate of Product 2],[Rate of Product 3])
) AS up3;