【发布时间】:2020-08-14 15:35:46
【问题描述】:
我正在尝试将多个相同类型的记录合并到 SQL 中的单行中。这是我的示例数据。我还尝试使用 COALESCE(Name + ',', '') AS Names,将它们合并在一起,然后在一个公用表中再次拆分它们。但是,这有点像合并第二行记录并在其上进行透视。
对此的任何意见都会有所帮助。谢谢!
Type| Name | Department | Value1 | Value 2 | Value 3
-----------------------------------------------------
1 | John | A | 100 | NULL | NULL
1 | John | B | NULL | 200 | NULL
1 | John | C | NULL | NULL | 300
2 | Kay | A | 400 | NULL | NULL
2 | Kay | B | NULL | 500 | NULL
3 | Lor | B | NULL | 600 | NULL
Edited: Apologies for not properly articulating my original problem. Updated below again.
Here is the transformation output looking after the query. Given departments can be many and they are transformed to only 3 columns in the output based on Dept Type.
ID | Name | Department1 | Department 2| Department 3 | Value1 | Value 2 | Value 3
-----------------------------------------------------
1 | John | A | B | C | 100 | 200 | 300
2 | Kay | A | B | NULL | 400 | 500 | NULL
3 | Lor | NULL | B | NULL | NULL | 600 | NULL
I was trying with below query, but i am not able to transform department values into column values.
SELECT
ID,
MAX(Value1) AS Value1,
MAX(Value2) AS Value2,
MAX(Value3) AS Value3
FROM Employee
GROUP BY Name ```>
【问题讨论】:
-
顺便说一句,您的示例输出没有意义。部门 B 应该是部门 2,不是吗?
-
是的,这是一个错字并更新了我的问题。感谢您的关注。
标签: sql-server merge