Solved

SQL Pivot Result

Posted on 2014-01-22
10
344 Views
Last Modified: 2014-01-22
Dear Experts,
I have a attached store procedure to display records as Pivot Table. this is showing perfect data only creating issue to convert PaidUnPaid Column into converting

if i replaced 'Paid' to -1 then its run perfectly
When i placed 'Paid' instead of numeric its not run

My SQL is as follows:
Drop Table #tempFeePaidUnPaidDetail

Select a.StudentId
  , b.GRNNo
  , b.ParentId
  , b.StudentName
  , c.FatherName
 , Class = e.ClassName  
  , Section = f.SectionName
  , Shift = g.ShiftName  
  , d.RollNo 
 
  , MonthNames= left(case when ftm.MonthNo is null then DateName( month , DateAdd( month , a.MonthNo, -1 )) else DateName( month , DateAdd( month , ftm.MonthNo, -1 )) end  ,3)
   , PaidUnPaid=Case When (a.Credit -Isnull((select Debit=SUM(debit) from FeeTransactionsMonth xx 
				Where xx.MonthNo=a.monthNo and xx.FiscalYearId=a.fiscalyearid and xx.TransId=a.TransId Group by TransID, MonthNo,FiscalYearId),0))=0 then
				'Paid' else CONVERT(Varchar(10),a.Credit) end
    --case when ftm.TransId is null then a.Credit 
	--				 When (a.Credit - isnull(ftm.Debit,0)) = 0  then '0'
	--				 Else (a.Credit - isnull(ftm.Debit,0)) end
	,MonthNo = case when ftm.MonthNo is null then convert(varchar,a.MonthNo) else convert(varchar,ftm.MonthNo) end
Into #tempFeePaidUnPaidDetail
from FeeTransactions a
Join Students b on a.StudentId =b.StudentId 
Left Outer Join Parents c on b.ParentId =c.ParentID 
Left Outer Join StudentYearRecord d on a.StudentId =d.StudentId and a.CampusId=d.CampusID and a.FiscalYearId=d.YearID
Join Classes e  on d.PC=e.ClassId 
Join Sections f on d.Section=f.SectionId 
join Shifts g on d.Shift=g.ShiftId 
left join FeeTransactionsMonth ftm on (ftm.TransId = a.TransId)
Where a.Credit >0 
and a.FiscalYearID=1
and (b.PresentClassId like 1)
--and (b.PresentSectionId like @SectionId)
--and (b.PresentShiftId like @ShiftId)
--and (b.GRNNo like @GRNNo)
and b.FeeTerm not in (2)
Order by e.ClassName  
  , f.SectionName 
  , g.ShiftName, d.RollNo
 
 
Exec CrossTabMake 'Select StudentId,GRNNo,ParentId,StudentName,FatherName,Class,Section,Shift,RollNo,MonthNames,MonthNo,PaidUnPaid From #tempFeePaidUnPaidDetail'
,'MonthNo+MonthNames'
,'sum(PaidUnPaid)[]'
,'StudentId,GRNNo,ParentId,StudentName,FatherName,Class,Section,Shift,RollNo'
,''
,'Class,Section,Shift,RollNo'

Open in new window




USE [RHGS2]
GO
/****** Object:  StoredProcedure [dbo].[CrossTabMake]    Script Date: 01/22/2014 22:05:19 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER procedure [dbo].[CrossTabMake] ( 
@SQL nvarchar(4000), 
@PivotCol varchar(100), 
@Summaries varchar(100), 
@GroupBy varchar(100), 
@OtherFields varchar(100) = '', 
@OrderByFields varchar(100) = '', 
@rollup bit = 0, 
@Debug bit = 0) 
AS 

--Exec SearchAllTables 'CrossTabMake'
set nocount on 
set ansi_warnings off 

declare @Vals varchar(8000); 
declare @Vals2 varchar(8000); 
declare @Vals3 varchar(8000); 
declare @tmp varchar(1000); 
declare @TotalLen int; 
declare @roll varchar(20); 

set @Vals = ''; 
set @Vals2 = ''; 
set @Vals3 = ''; 
set @TotalLen = len(@SQL) + len(@GroupBy) + Len(@OtherFields) + Len(@OrderByFields) 

if (@OtherFields <> '') 
begin 
set @OtherFields = ', ' + @OtherFields 
end 

if (@OrderByFields <> '') 
begin 
set @OrderByFields = ' order by ' + @OrderByFields 
end 

set @roll = CASE @rollup WHEN 1 THEN ' WITH ROLLUP' ELSE '' END 

create table #temp (thisPivot varchar(100)) 

insert into #temp 
exec ('select distinct convert(varchar(100),' + @PivotCol + ') as thisPivot FROM (' + @SQL + ') A') 
select @tmp = 
replace(replace(@Summaries,'(','(CASE WHEN ' + @PivotCol + '=''' + replace(thisPivot,'''','''''') + 
''' THEN '),')[', ' END) as [' + thisPivot ), 
@TotalLen = @TotalLen + Len(@tmp), 
@Vals = case when @TotalLen < 7800 then @Vals + ', ' + @tmp else @Vals end, 
@Vals2 = case when @TotalLen between 7800 and 15799 then @Vals2 + ', ' + @tmp else @Vals2 end, 
@Vals3 = case when @TotalLen between 15800 and 23799 then @Vals3 + ', ' + @tmp else @Vals3 end 
from 
#Temp 
order by 
thisPivot 

drop table #Temp 

if (@Debug=0) 
exec( 'select ' + @GroupBy + @OtherFields + @Vals + @Vals2 + @Vals3 + 
' from (' + @SQL + ') A GROUP BY ' + @GroupBy + @roll + @OrderByFields) 
else 
begin 
print( 'select ' + @GroupBy + @OtherFields + @Vals + @Vals2 + @Vals3 + 
' from (' + @SQL + ') A GROUP BY ' + @GroupBy + @roll + @OrderByFields) 
end 

set nocount off 
set ansi_warnings on

Open in new window

0
Comment
Question by:Mehram
  • 6
  • 4
10 Comments
 

Author Comment

by:Mehram
ID: 39800521
result
0
 
LVL 59

Expert Comment

by:Kevin Cross
ID: 39800609
I may not be following the logic completely, but it appears you are passing to your procedure the first query and asking it to SUM(PaidUnPaid) column.  Therefore, if you make it 'Paid' in the first query, it should not work.  Try making this column just the difference in debts and credits as a number value, then in the final select use CASE statement (or ISNULL-NULLIF combination) to replace 0 with 'Paid'.
0
 

Author Comment

by:Mehram
ID: 39800627
I have tried to do something like this but no luck

Exec CrossTabMake 'Select StudentId,GRNNo,ParentId,StudentName,FatherName,Class,Section,Shift,RollNo,MonthNames,MonthNo,
					PaidUnPaid=Case When PaidUnPaid>0 then PaidUnPaid else ''-0'' end From #tempFeePaidUnPaidDetail'
,'MonthNo+MonthNames'
,'Sum(PaidUnPaid)[]'
,'StudentId,GRNNo,ParentId,StudentName,FatherName,Class,Section,Shift,RollNo'
,''
,'Class,Section,Shift,RollNo'

Open in new window

0
 
LVL 59

Expert Comment

by:Kevin Cross
ID: 39800646
What is the error message it is giving you?  To debug, you can PRINT out the dynamic SQL you are creating.  You may spot the issue more easily that way.
0
 

Author Comment

by:Mehram
ID: 39800655
I have change SQL

Please to see screen with error
0
[Webinar] Disaster Recovery and Cloud Management

Learn from Unigma and CloudBerry industry veterans which providers are best for certain use cases and how to lower cloud costs, how to grow your Managed Services practice in IaaS clouds, and how to utilize public cloud for Disaster Recovery

 

Author Comment

by:Mehram
ID: 39800656
error
0
 
LVL 59

Accepted Solution

by:
Kevin Cross earned 500 total points
ID: 39800693
It is as I suspected.  It will not work that way.  If you only expect one value, you could try MAX as the aggregate.  If you need the SUM, then leave paid as zero, so SUM will be zero.  That way you can use COALESCE(CONVERT(VARCHAR(10), NULLIF(pivot_column, 0)), 'Paid') on each of the pivoted columns.
0
 

Author Comment

by:Mehram
ID: 39800700
Sir can you change it my query
0
 

Author Comment

by:Mehram
ID: 39800709
Its worked sir
expected value was only one


Exec CrossTabMake 'Select StudentId,GRNNo,ParentId,StudentName,FatherName,Class,Section,Shift,RollNo,MonthNames,MonthNo,
					PaidUnPaid=Case When PaidUnPaid=0 then ''Paid'' else Convert(Varchar(10),PaidUnPaid) end From #tempFeePaidUnPaidDetail'
,'MonthNo+MonthNames'
,'Max(PaidUnPaid)[]'
,'StudentId,GRNNo,ParentId,StudentName,FatherName,Class,Section,Shift,RollNo'
,''
,'Class,Section,Shift,RollNo'

Open in new window

0
 
LVL 59

Expert Comment

by:Kevin Cross
ID: 39800716
I am glad you got it and that I could help.

Best regards and happy coding,

Kevin
0

Featured Post

Control application downtime with dependency maps

Visualize the interdependencies between application components better with Applications Manager's automated application discovery and dependency mapping feature. Resolve performance issues faster by quickly isolating problematic components.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

After restoring a Microsoft SQL Server database (.bak) from backup or attaching .mdf file, you may run into "Error '15023' User or role already exists in the current database" when you use the "User Mapping" SQL Management Studio functionality to al…
If you have heard of RFC822 date formats, they can be quite a challenge in SQL Server. RFC822 is an Internet standard format for email message headers, including all dates within those headers. The RFC822 protocols are available in detail at:   ht…
Internet Business Fax to Email Made Easy - With eFax Corporate (http://www.enterprise.efax.com), you'll receive a dedicated online fax number, which is used the same way as a typical analog fax number. You'll receive secure faxes in your email, fr…
Video by: Mark
This lesson goes over how to construct ordered and unordered lists and how to create hyperlinks.

895 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

12 Experts available now in Live!

Get 1:1 Help Now