ssms - SQL - Cross tab. Sum of a field instead of count rows in columns -
currently trying create query give me sales made agent day whole year. i've managed total column work, daily sales don't, looking @ raw data seems rather summing total sales made day particular agent instead counting rows agent listed , outputting instead. code follows:
declare @cols nvarchar(max), @query nvarchar(max) select @cols = stuff((select ',' + quotename(convert(varchar(20), [entry_date], 106)) [sales_data] (nolock) where([entry_date] between '01-jan-2017' , '01-jul-2017' group [entry_date] order [entry_date] xml path(''), type ).value('.', 'nvarchar(max)') ,1,1,'') set @query = ' select [advisor_name] [advisor_name] ,[line_managers_name] [line_managers_name] ,[sale_type] ,[total] ,'+ @cols +' ( select sum([sales]) over(partition [advisor_name], [line_managers_name], [sale_type]) [total] , [entry_date] , [advisor_name] , [line_managers_name] , [sale_type] [sales_data] (nolock) ) x pivot ( count([entry_date]) [entry_date] in (' + @cols + ') ) p order [advisor_name], [line_managers_name], [channel] ' execute(@query)
if couldn't change query had planned on instead altering source data give me line line sale info rather aggregating sum, unfortunately of rows might have customer -1 sale indicate refund , don't know how accommodate these, have tried select distinct, select (select distinct.....) having count(*) = 1, nothing seems want work.
i've amended our dynamically generated sql generate new output.
declare @cols nvarchar(max) declare @colsforpivot nvarchar(max) declare @query nvarchar(max) select @cols = stuff((select ',isnull(' + quotename(convert(varchar(20), [entry_date], 106)) + ',0)' [sales_data] (nolock) where([entry_date] between '01-jan-2017' , '01-jul-2017') group [entry_date] order [entry_date] xml path(''), type ).value('.', 'nvarchar(max)') ,1,1,'') select @colsforpivot = stuff((select ',' + quotename(convert(varchar(20), [entry_date], 106)) [sales_data] (nolock) where([entry_date] between '01-jan-2017' , '01-jul-2017') group [entry_date] order [entry_date] xml path(''), type ).value('.', 'nvarchar(max)') ,1,1,'') set @query = 'select [advisor_name], [line_managers_name], [sale_type], isnull(totalsales,0), ' + @cols + ' ( select distinct sum([sales]) over(partition [advisor_name], [line_managers_name], [sale_type], [entry_date]) [total] , [entry_date] , [advisor_name] , [line_managers_name] , [sale_type], sum([sales]) over(partition [advisor_name], [line_managers_name], [sale_type]) totalsales [sales_data] (nolock) ) x pivot ( sum([total]) [entry_date] in (' + @colsforpivot + ') ) p order [advisor_name], [line_managers_name] ' print(@query)
Comments
Post a Comment