表格结构
Item, Group, Min Qty, Price
A, 1, 10, 1.00
A, 2, 10, 0.75
B, 1, 20, 0.90
C, 3, 5, 5.00
我正在运行的SQL查询,它适用于所有组,分为1列,我正在尝试找出如何为每个组添加一个列,并且只放入该组中的值。
SELECT [Item],
STUFF((
SELECT ', ' + CAST([Min Qty] AS VARCHAR(MAX)) + ':' + CAST([Price] AS VARCHAR(MAX) + ';')
FROM [Table] WHERE ([Item No_] = Results.[Item] and [Minimum Qty] > '1')
FOR XML PATH(''),TYPE
).value('.','VARCHAR(MAX)')
,1,2,'') as Values
FROM [Table] Results
GROUP BY [Item]
当前输出
Item, Values
A, 10:0.75; 10:1.00;
B, 20:0.90;
C, 5:5.00;
必需的输出
Item, Group 1, Group 2, Group 3
A, 10:1.00; 10:0.75;
B, 20:0.90;
C, 5:5.00;
感谢您输入
从下面编辑
我们不知道所有列名称,因为它们将被其他用户添加到系统中,因此需要自动添加列也应该将该组/项的所有条目分组为1列,因为我正在尝试生成输出文件。
表格信息
Item, Group, Min Qty, Price
A, 1, 10, 1.00
A, 2, 10, 0.75
B, 1, 20, 0.90
C, 3, 5, 5.00
A, 1, 20, 0.50
Item, Group 1, Group 2, Group 3
A, 10:1.00;20:0.50; 10:0.75;
B, 20:0.90;
C, 5:5.00;
答案 0 :(得分:2)
declare @t table (Item Varchar(2),Groups Varchar(2),MInqty varchar(10),Price Money)
insert into @t (Item,Groups,MInqty,Price)values
('A,','1,',10,1.00),
('A,','2,',10,0.75),
('B,','1,',20,0.90),
('C,','3,',5,5.00)
select Item,[1,] AS [Groups 1],[2,] AS [Groups 2],[3,] AS [Groups 3]
from (
select Item,Groups,MInqty +':'+ CAST(price AS VARCHAR) + ';' As GRP from @t)P
PIVOT (MIN(GRP) FOR GROUPS IN ([1,],[2,],[3,]))PVT
重新修改的答案检查
Select Item,[1] AS [Groups 1],[2] AS [Groups 2],[3] AS [Groups 3] from (
Select P.Item,MIN(R)G,P.Value from (
SELECT [Item],SUBSTRING(Groups,0,CHARINDEX(',',Groups))R,
STUFF((
SELECT ', ' + CAST([MInqty] AS VARCHAR(MAX)) + ':' + CAST([Price] AS VARCHAR(MAX) )+';'As Grp
FROM #t WHERE ([Item] = Results.[Item] and [MInqty] > '1')
FOR XML PATH(''),TYPE
).value('.','VARCHAR(MAX)')
,1,2,'') as Value
FROM #t Results
GROUP BY Groups,Item)P
GROUP BY P.Item,p.Value)PP
PIVOT (MIN(Value)FOR G IN ([1],[2],[3]) )PVT