sql - One column into multiple columns by type, plus concatenating multiples
问题描述
I have a table like this:
Customer | Number | Type |
---|---|---|
1 | 234.567.8910 | 1 |
1 | 234.234.2345 | 2 |
2 | 234.567.5555 | 1 |
2 | 151.513.5464 | 1 |
3 | 845.846.8486 | 3 |
I am trying to include this information with information from another table (say... address), but in separate columns by type, and I want to concatenate values that are of the same type so that the return looks like this:
Customer | Cell | Home | Work |
---|---|---|---|
1 | 234.567.8910 | 234.234.2345 | NULL |
2 | 234.567.5555 & 151.513.5464 | NULL | NULL |
3 | NULL | NULL | 845.846.8486 |
When I use the STRING_AGG function, it appends the value for each line of that customer - even if it would be null when the function isn't applied, so the customer 1 has both the cell and home numbers repeated twice.
The only workaround I can find is to select each column in a subquery and join them together. Is that the only option?
解决方案
尝试使用FOR XML
和PATH
。
询问
select [Customer],
stuff((
select distinct ',' + [Number]
from [your_table_name]
where [Customer] = a.[Customer]
and [Type] = 1
for xml path (''))
, 1, 1, '') as [Cell],
stuff((
select distinct ',' + [Number]
from [your_table_name]
where [Customer] = a.[Customer]
and [Type] = 2
for xml path (''))
, 1, 1, '') as [Home],
stuff((
select distinct ',' + [Number]
from [your_table_name]
where [Customer] = a.[Customer]
and [Type] = 3
for xml path (''))
, 1, 1, '') as [Work]
from [your_table_name] as a
group by [Customer];
推荐阅读
- asciidoc - 如何使用 Asciidoctor 获得文字块的行号?
- python - ModuleNotFoundError:没有名为“src”的模块。从没有 sys.path 的另一个目录导入模块并从现有目录执行它们
- javascript - 我在 CytoscapeComponent 中编写的 console.log 的工作次数与我单击 cy 屏幕时单击屏幕上的按钮的次数一样多
- python - 如何模拟在模拟对象上调用的函数,以返回特定值
- php - PHP循环槽文件夹并删除旧文件/空文件夹
- electron - 节点通知程序在生产中不工作 | 我做错了什么?
- reactjs - 我们可以在 React 应用程序中覆盖 webpack DefinePlugin 的变量吗
- node.js - Runtime.HandlerNotFound aws lambda node.js
- css - 如何使用滚动捕捉 CSS 控制/更改动画的速度?
- python - Tableview 列自动调整