SQL - 转向还是逆转向?

SQL - Pivot or Unpivot?

另一次,另一个问题。我有以下 table:

|assemb.|Repl_1|Repl_2|Repl_3|Repl_4|Repl_5|Amount_1|Amount_2|Amount_3|Amount_4|Amount_5|
|---------------------------------------------------------------------------------------|
|4711001|111000|222000|333000|444000|555000|       1|       1|       1|       1|       1|
|---------------------------------------------------------------------------------------|
|4711002|222000|333000|444000|555000|666000|       1|       1|       1|       1|       1|
|---------------------------------------------------------------------------------------|

这是我需要的:

|Article|Amount|
|--------------|
| 111000|     1|
|--------------|
| 222000|     2|
|--------------|
| 333000|     2|
|--------------| 
| 444000|     2|
|--------------| 
| 555000|     2|
|--------------|
| 666000|     1|
|---------------

Repl_1到Repl_10是组件的替换品。我可以有 n 个程序集最多 10 个 rep-articles。最后,我需要概述所有包含所有程序集的文章。

谢谢。

最好的问候语 贝吉塔

这可能是使用 UNION ALL 实现它的最快方法。但是,我建议您规范化 table

SELECT Article, SUM(Amount) FROM (
    SELECT Repl_1 AS Article, SUM(Amount_1) AS Amount FROM #Test GROUP BY Repl_1
    UNION ALL
    SELECT Repl_2 AS Article, SUM(Amount_2) AS Amount FROM #Test GROUP BY Repl_2
    UNION ALL
    SELECT Repl_3 AS Article, SUM(Amount_3) AS Amount FROM #Test GROUP BY Repl_3
    UNION ALL
    SELECT Repl_4 AS Article, SUM(Amount_4) AS Amount FROM #Test GROUP BY Repl_4
    UNION ALL
    SELECT Repl_5 AS Article, SUM(Amount_5) AS Amount FROM #Test GROUP BY Repl_5
) tbl GROUP BY Article