如何将单列逗号分隔值拆分为多列,并将左联合分离到MySQL中另一个表的每个单元格?

时间:2017-06-06 18:29:08

标签: mysql mysqli phpmyadmin

我需要一个在MySQL中创建视图的解决方案。 我有两个数据表。一个有客户名单。

Table: name_list
Id          Name
------------------
12345       Steve
23456       Mick
34567       Robert
45678       John
56789       Taylor
67890       Steven
23234       Ken
56746       Harry

另一个有客户群。

Table: customer_group
Group       Customers
----------------------
A5213       12345,34567,56789
B5314       23234
D5486       23456,45678,67890,56746

现在我需要通过将逗号分隔的客户ID与customer_group表分开来显示这些数据,并从name_list表中加入这些客户的名称。

View: customer_name_result
Group   Cust1   Name1   Cust2   Name2   Cust3   Name3   Cust4   Name4
----------------------------------------------------------------------
A5213   12345   Steve   34567   Robert  56789   Taylor  NULL    NULL
B5314   23234   Ken     NULL    NULL    NULL    NULL    NULL    NULL
D5486   23456   Mick    45678   John    67890   Steven  56746   Harry

提前感谢您的帮助。

1 个答案:

答案 0 :(得分:0)

您可以使用以下角色:

;with cte as (
    select [Group], [Value], nl.[name], RowN = Row_Number() over(partition by [Group] order by [Value]) 
        ,RowN1 = Row_Number() over(partition by [Group] order by [Value]) +1000
        from customer_group cg
    cross apply
    (
        Select * from string_split(customers,',')
    ) a
    inner join name_list nl
    on a.value = nl.id
)  
select [Group],   max([1001]) as [Name1], max([1]) as [Val1] 
                , max([1002]) as [Name2], max([2]) as [Val1]
                , max([1003]) as [Name3], max([3]) as [Val1]
                , max([1004]) as [Name4], max([4]) as [Val1]
from
(select * from cte ) b  
pivot (max([value]) for RowN in([1],[2],[3],[4])) p
pivot (max([name]) for RowN1 in ([1001],[1002],[1003],[1004])) p1
group by [Group]

回答如下:

+-------+--------+-------+--------+-------+--------+-------+--------+-------+
| Group | Name1  | Val1  | Name2  | Val1  | Name3  | Val1  | Name4  | Val1  |
+-------+--------+-------+--------+-------+--------+-------+--------+-------+
| A5213 | Steve  | 12345 | Robert | 34567 | Taylor | 56789 | NULL   | NULL  |
| B5314 | Ken    | 23234 | NULL   | NULL  | NULL   | NULL  | NULL   | NULL  |
| D5486 | Mick   | 23456 | John   | 45678 | Harry  | 56746 | Steven | 67890 |
+-------+--------+-------+--------+-------+--------+-------+--------+-------+