共有4个表:
Suppl ,字段:( Code_name,Code_name_arch,Tasknum,Pki_num,Group_eng,Name,Descr,Cost,Quan,shop);
制作者,字段:(Code_maker,Code_maker_arch,Code_name,provider);
到达,字段:(Code_arr,Code_maker,quan_arr);
帐户,字段:(Code_acc,Code_maker,num_acc,quan_acc,summ)
我的查询是:
ALTER Procedure [dbo].[pr_tblz] As
Set NOCOUNT ON
Declare @task VARCHAR(4000)
Select @task = coalesce(@task + ',[' + [Tasknum] + ']',
'[' + [Tasknum] + ']')
FROM [db_pki].[dbo].[Suppl]
Group BY [Tasknum]
Order BY [Tasknum]
Declare @query VARCHAR(8000)
Set @query='
Alter View Amountzz As
SELECT Shop, Name, Desc, Group_eng as GI, '+ @task +', quan_arr As specif, quan_acc As acns
FROM
(
select
Shop, Name, Desc, Group_eng, Tasknum, Quan, quan_arr, quan_acc
from [db_pki].[dbo].[Suppl] as deliveries
LEFT JOIN [db_pki].[dbo].[Maker] ON (deliveries.[Code_name] = [db_pki].[dbo].[Maker].[Code_name])
LEFT JOIN [db_pki].[dbo].[Arrival] ON ([db_pki].[dbo].[Maker].[Code_maker] = [db_pki].[dbo].[Arrival].[Code_maker])
LEFT JOIN [db_pki].[dbo].[Accounts] ON ([db_pki].[dbo].[Maker].[Code_maker] = [db_pki].[dbo].[Accounts].[Code_maker])
)date_to_pivot
PIVOT
(
Max([Quan])
For [Tasknum]
IN (' + @task + ')
)AS p'
Execute (@query)
结果:
Shop Name Descr GI n1 n2 n3 ... specif acns
1 name1 1 5 4 1 1
2 10 name2 2 3 8 2 2
3 name3 3 501 11 3 3
1 8 name1 1 5 16 7 10
a 2 10 name2 2 3 3 5 6
5 name1 1 2 5 6 3
如何获得以下结果?
Shop Name Descr GI n1 n2 n3 ... specif acns
1 8 name1 1 5 4 16 8(1+7) 11
a 2 10 name2 2 3 8 3 7 8(2+6)
3 name3 3 501 11 3 3
5 name1 1 2 5 6 3
n1,n2,n3,... - Tasknum
答案 0 :(得分:0)
未经过测试。尝试在旋转前拉取列的子选择中聚合Shop
,specif
和acns
的值,如下所示(必要的更改以粗体突出显示:
ALTER Procedure [dbo].[pr_tblz] As
Set NOCOUNT ON
Declare @task VARCHAR(4000)
Select @task = coalesce(@task + ',[' + [Tasknum] + ']',
'[' + [Tasknum] + ']')
FROM [db_pki].[dbo].[Suppl]
Group BY [Tasknum]
Order BY [Tasknum]
Declare @query VARCHAR(8000)
Set @query='
Alter View Amountzz As
SELECT Shop, Name, Desc, Group_eng as GI, '+ @task +', quan_arr As specif, quan_acc As acns
FROM
(
select
MAX(Shop ) OVER (PARTITION BY Name) AS Shop,
Name, Desc, Group_eng, Tasknum, Quan,
SUM(quan_arr) OVER (PARTITION BY Name) AS quan_arr,
SUM(quan_acc) OVER (PARTITION BY Name) AS quan_acc
from [db_pki].[dbo].[Suppl] as deliveries
LEFT JOIN [db_pki].[dbo].[Maker] ON (deliveries.[Code_name] = [db_pki].[dbo].[Maker].[Code_name])
LEFT JOIN [db_pki].[dbo].[Arrival] ON ([db_pki].[dbo].[Maker].[Code_maker] = [db_pki].[dbo].[Arrival].[Code_maker])
LEFT JOIN [db_pki].[dbo].[Accounts] ON ([db_pki].[dbo].[Maker].[Code_maker] = [db_pki].[dbo].[Accounts].[Code_maker])
)date_to_pivot
PIVOT
(
Max([Quan])
For [Tasknum]
IN (' + @task + ')
)AS p'
Execute (@query)