SQL使用特定输入查找对应的列并创建新的汇总表

问题描述

数据是平面归一化表:

|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;

相关问答

依赖报错 idea导入项目后依赖报错,解决方案:https://blog....
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下...
错误1:gradle项目控制台输出为乱码 # 解决方案:https://bl...
错误还原:在查询的过程中,传入的workType为0时,该条件不起...
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct...