Mal*_*lik 3 sql sql-server string concatenation
我已经浪费了整整两天的时间来试图解决这个问题,现在我想出了我的想法,我需要一个紧急的帮助,问题是,我有桌子
表:Sales,SalesId是primary key
---------------------------------------------------
SalesId | SalesDate | Customer| Discount | Remarks
---------------------------------------------------
1 | 01/01/2012| John | 15 | NULL
2 | 01/01/2012| Peter | 25 | NULL
3 | 01/01/2012| Micheal | 35 | NULL
Run Code Online (Sandbox Code Playgroud)
表:SalesBody,的SerialNo是primary key和SalesId是foreign key
---------------------------------------------------
SerialNo | SalesId | Product | Quantity | Rate
---------------------------------------------------
10 | 1 | Pencil | 18 | 20
11 | 1 | pen | 200 | 60
12 | 1 | Rubber | 150 | 10
13 | 1 | Paper | 500 | 2
14 | 2 | Mouse | 15 | 190
15 | 2 | KeyBoard | 10 | 600
16 | 2 | Monitor | 5 | 2000
17 | 3 | Mobile | 2 | 15000
Run Code Online (Sandbox Code Playgroud)
现在我想做一个可以使结果如下的查询
----------------------------------------------------------------------------
SalesId | SalesDate | Details | Amount
----------------------------------------------------------------------------
1 | 01/01/2012 | Sold: Pencil x 18 @ 20, Pen x 200 @ 60| xxxxxxx
| | Rubber x 150 @ 10, Paper x 500 @ 2 |
2 | 01/01/2012 | Sold: Mouse x 15 @ 190, Keyboard x 10 |
| | @ 600, Monitor x 5 @ 2000 | xxxxxxx
3 | 01/01/2012 | Sold: Mobile x 2 @ 15000 | xxxxxxx
Run Code Online (Sandbox Code Playgroud)
我尝试过不同的技术,例如.Coalesce,Stuff,用于XML路径('')
我无法连接细节字符串.
小智 6
据我所知,您只需要通过SalesID来旋转SalesBody表和组
以下查询的某些内容应该可以解决问题
select sb.SalesId, ( SELECT ', ' + sb2.Product + ' x ' + sb2.Quantity + ' @ ' + sb2.Rate
FROM SalesBody sb2
WHERE sb2.SalesId = sb.SalesId
FOR XML PATH('') ) AS Details
from SalesBody sb
group by sb.SalesId
Run Code Online (Sandbox Code Playgroud)
然后只需将该查询与Sales表连接即可获取其他数据,并在上面查询中的Details上执行STUFF命令,删除前导","并添加"sold:"字符串,您应该好好去.
| 归档时间: |
|
| 查看次数: |
19924 次 |
| 最近记录: |