Declare @a Table (Name Varchar(100),Loan Varchar(100),Balance int, LN_Date DateTime, A_Indicator varchar(100) Insert into @a select 'a','loan1',120, '201005', ‘a_indicator’ union select 'a','loan2',100, '201505', ‘a_indicator’ union select 'a','loan3',120, '201205', ‘a_indicator’ union select 'a','loan4',150, '201505', ‘a_indicator’ union select 'b','loan1',10, '201505', ‘a_indicator’ union select 'b','loan2',20, '201205', ‘a_indicator’ union select 'b','loan3',150, '201005', ‘a_indicator’ union SELECT 'c','loan1',50, '201505', ‘non_a_indicator’ union select 'c','loan2',10,' 201205', ‘non_a_indicator’ union select 'c','loan3',80, '201505', ‘non_a_indicator’
I have a SQL db with number of loans for each customer and their current balance for past five years. ( The date part has year, month). The Max current unpaid balance customer is Rank 1 and will be in the first row and first column.The number of loans is displayed in the second group by year.The third group will have the current balance by year.The fourth group contains the Rank of this customer in each year.The last column contains the current year rank of the customer. All the Table data should be sorted by the Year 1 Rank and by year
The customers a,b should be in one group, other customers are in a different group.The a, b customers have higher rank than C.
Theresult is not sorted correct. It should besorted by rank of year 1, a_indicator and date only.
The number of loans count is zero after second year. But the actual data in loan table has the data.
Need to select one more column A_INDICATOR
Need to pass the years from c# and the data should be selected for those dates.
Need to have a indicator total row for the a indicator group as shown in the result. Also Non a indicator total row should be there
;WITH t AS ( SELECT * , DENSE_RANK()OVER( PARTITION BY [Customer_Name] ORDER BY YEAR([LN_Date]) DESC) AS rn_YEAR FROM LN_INFO_TABLE ) SELECT * , DENSE_RANK()OVER( ORDER BY [Year_1_curBalance] desc ) AS [Year_1_Rank] , DENSE_RANK()OVER( ORDER BY [Year_2_curBalance] desc ) AS [Year_2_Rank] , DENSE_RANK()OVER( ORDER BY [Year_3_curBalance] desc ) AS [Year_3_Rank] FROM ( SELECT Customer_Name,ISNULL([1],0) AS [Year_1_LoanCount],ISNULL([2],0) AS [Year_2_LoanCount],ISNULL([3],0) AS [Year_3_LoanCount] FROM ( SELECT Customer_Name,[Loan],rn_YEAR FROM t ) t PIVOT ( COUNT( [Loan]) FOR rn_YEAR IN ([1],[2],[3]) ) AS pvt ) AS LoanCnt JOIN ( SELECT Customer_Name,ISNULL([1],0) AS [Year_1_curBalance],ISNULL([2],0) AS [Year_2_curBalance],ISNULL([3],0) AS [Year_3_curBalance] FROM ( SELECT Customer_Name,Balance,rn_YEAR FROM t ) t PIVOT ( SUM( Balance) FOR rn_YEAR IN ([1],[2],[3]) ) AS pvt ) AS Balance ON LoanCnt.Customer_Name = Balance.Customer_Name ORDER BY 1