PIVOT Query
Create Table
CREATE TABLE [dbo].[test01](
[id] [int] NOT NULL,
[group_id] [int] NULL,
[name] [varchar](50) NULL,
[qty] [int] NULL,
[newqty] [int] NULL,
CONSTRAINT [PK_test01] PRIMARY KEY CLUSTERED
(
[id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
Insert Data
INSERT INTO [dbo].[test01] VALUES (1,1,'A',13,1)
INSERT INTO [dbo].[test01] VALUES (2,1,'B',22,2)
INSERT INTO [dbo].[test01] VALUES (3,1,'C',14,3)
INSERT INTO [dbo].[test01] VALUES (4,2,'B',35,4)
INSERT INTO [dbo].[test01] VALUES (5,2,'C',20,5)
id group_id name qty newqty
1 1 A 13 1
2 1 B 22 2
3 1 C 14 3
4 2 B 35 4
5 2 C 20 5
Query
select *
from
(select group_id,name,qty from test01) src
pivot
( sum(qty) for name in ([A],[B],[C]) ) piv
OR
DECLARE @cols AS VARCHAR(MAX),
@query AS VARCHAR(MAX)
select @cols = STUFF(
( SELECT ',' + QUOTENAME(name) from test01 group by name order by name
FOR XML PATH(''), TYPE
).value('.', 'VARCHAR(MAX)')
,1,1,'')
set @query = '
SELECT group_id,' + @cols + '
FROM
(select group_id,name,qty from test01) src
PIVOT
(sum(qty) for name in (' + @cols + ')) pvt
'
execute(@query);
Result
group_id A B C
1 13 22 14
2 NULL 35 20
Comments
Post a Comment