我有一个表(tblproduct),其中包含字段:dept,product,qty。 以下样本数据:
dept product qty
IT A 2
IT B 1
PU C 4
SAL D 1
SER D 2
SER A 4
我想在sql server中创建存储的pro,结果如下:
product qty remark
A 6 IT=2,SER=4
B 1 IT=1
C 4 PU=4
D 3 SAL=1,SER=2
这是我存储的专业人士
select product,
sum(qty)
from tblproduct
group by product
order by product
PLS。任何帮助。感谢。
答案 0 :(得分:2)
SELECT
[product], SUM(qty) Total_Qty,
STUFF(
(SELECT ',' + dept + '=' + CAST(qty AS VARCHAR(10))
FROM TableName
WHERE [product] = a.[product]
FOR XML PATH (''))
, 1, 1, '') AS Remark
FROM TableName AS a
GROUP BY [product]
输出
╔═════════╦═══════════╦═════════════╗
║ PRODUCT ║ TOTAL_QTY ║ REMARK ║
╠═════════╬═══════════╬═════════════╣
║ A ║ 6 ║ IT=2,SER=4 ║
║ B ║ 1 ║ IT=1 ║
║ C ║ 4 ║ PU=4 ║
║ D ║ 3 ║ SAL=1,SER=2 ║
╚═════════╩═══════════╩═════════════╝
答案 1 :(得分:0)
请尝试:
SELECT product, SUM(qty) Qty,
STUFF(
(SELECT ','+b.dept+'='+CAST(qty as nvarchar(10))
FROM YourTable b where b.product=a.product
FOR XML PATH(''),type).value('.','nvarchar(max)'), 1, 1, '')
from YourTable a
group by product