在SQL中以不同的模式将两行合并为单行

问题描述

我正在尝试将多个相同类型的记录合并到sql中的单行中。这是我的样本数据。我还尝试过使用COALESCE(Name +',','')AS名称方法是将它们合并在一起,然后再次将它们拆分到一个公用表中。但是,这是合并第二行记录并在其上进行数据透视。

对此进行任何输入都会有所帮助。谢谢!

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

解决方法

您可以这样做:

SELECT 
   ID,Name,Max(case when department = 'A' then 'A' end) as Department1,Max(case when department = 'B' then 'B' end) as Department2,Max(case when department = 'C' then 'C' end) as Department3,MAX(Value1) AS Value1,MAX(Value2) AS Value2,MAX(Value3) AS Value3 
FROM Employee
GROUP BY Id,Name;

认为它只是用于某种枢轴,例如显示。

更新:我不太确定您的意思是否与示例中的意思相同(如果您的问题很清楚,那会很好):

WITH
  x AS (
         SELECT
              Name,Department,DENSE_RANK() OVER (PARTITION BY Name ORDER BY Department) AS dept
         FROM Employee
       )
SELECT
         t.Type                                        AS ID,t.Name,MAX(CASE WHEN x.dept=1 THEN x.Department END) AS Department1,MAX(CASE WHEN x.dept=2 THEN x.Department END) AS Department2,MAX(CASE WHEN x.dept=3 THEN x.Department END) AS Department3,MAX(Value1)                                   AS Value1,MAX(Value2)                                   AS Value2,MAX(Value3)                                   AS Value3
FROM     Employee t
         INNER JOIN x ON x.Name=t.Name
GROUP BY t.Type,t.Name
ORDER BY t.Name;

DBFiddle demo is here