0

数据是一个平面标准化表:

|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 的人来说,这很容易

4

2 回答 2

2

您可以使用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
于 2020-10-20T09:39:32.033 回答
0

使用 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;
于 2020-10-21T05:54:32.450 回答