试试这个。。。
表脚本和示例数据
CREATE TABLE [T1](
[bpm_no] [nvarchar](50) NULL,
[name] [nvarchar](50) NULL
)
CREATE TABLE [T2](
[bpm_no] [nvarchar](50) NULL,
[user] [nvarchar](50) NULL
)
CREATE TABLE [T3](
[bpm_no] [nvarchar](50) NULL,
[loan_os] [decimal](18, 0) NULL
)
INSERT [T1] ([bpm_no], [name]) VALUES (N'abc_0011', N'john')
INSERT [T2] ([bpm_no], [user]) VALUES (N'abc_0011', N'abc')
INSERT [T2] ([bpm_no], [user]) VALUES (N'abc_0011', N'bcd')
INSERT [T2] ([bpm_no], [user]) VALUES (N'abc_0011', N'lmn')
INSERT [T3] ([bpm_no], [loan_os]) VALUES (N'abc_0011', CAST(14500 AS Decimal(18, 0)))
INSERT [T3] ([bpm_no], [loan_os]) VALUES (N'abc_0011', CAST(4000 AS Decimal(18, 0)))
INSERT [T3] ([bpm_no], [loan_os]) VALUES (N'abc_0011', CAST(5000 AS Decimal(18, 0)))
查询
SELECT t1.bpm_no,
sq1.[user],
sq2.loan_os
FROM t1
INNER JOIN (SELECT bpm_no,
Stuff((SELECT ', ' + [user]
FROM t2 t21
WHERE t21.bpm_no = t22.bpm_no
FOR xml path('')), 1, 2, '') AS [user]
FROM t2 t22
GROUP BY bpm_no) sq1
ON t1.bpm_no = sq1.bpm_no
INNER JOIN (SELECT bpm_no,
Sum(loan_os) AS loan_os
FROM t3
GROUP BY bpm_no) sq2
ON t1.bpm_no = sq2.bpm_no
注意:如果要获取所有
bpm_no
在里面
T1
主表中,使用左联接而不是内部联接。
查询(没有T1主表的相同预期结果)
SELECT sq1.bpm_no,
sq1.[user],
sq2.loan_os
FROM (SELECT bpm_no,
Stuff((SELECT ', ' + [user]
FROM t2 t21
WHERE t21.bpm_no = t22.bpm_no
FOR xml path('')), 1, 2, '') AS [user]
FROM t2 t22
GROUP BY bpm_no) sq1
INNER JOIN (SELECT bpm_no, Sum(loan_os) AS loan_os
FROM t3
GROUP BY bpm_no) sq2
ON sq1.bpm_no = sq2.bpm_no
输出
+----------+---------------+---------+
| bpm_no | user | loan_os |
+----------+---------------+---------+
| abc_0011 | abc, bcd, lmn | 23500 |
+----------+---------------+---------+
演示:
http://www.sqlfiddle.com/#!18/b6362/2/0
如果我被误解了,请告诉我。