Here is my code. Two CTES With a subquery and im trying to get the 2ns cte to give me totals like a pivot table.
WITH
SalesSummary AS
(
SELECT
Employee AS RepID,
Type,
SUM( ForeignTotal ) AS ForeignTotal,
SUM( projectedTotal*probability ) AS ProjectedTotal
FROM
Transaction
WHERE
( ( Type = 'SalesOrd' ) AND ( BUILTIN.CF( Status ) IN ('SalesOrd:B','SalesOrd:A') AND TO_CHAR(shipdate, 'mm') = TO_CHAR(sysdate, 'mm')
AND TO_CHAR(shipdate, 'yyyy') = TO_CHAR(sysdate, 'yyyy') ) )
OR ( ( Type = 'Opprtnty' ) AND ( BUILTIN.CF( Status ) IN ('Opprtnty:A','Opprtnty:C') AND TO_CHAR(expectedclosedate, 'mm') = TO_CHAR(sysdate, 'mm')
AND TO_CHAR(expectedclosedate, 'yyyy') = TO_CHAR(sysdate, 'yyyy') ) )
OR ( ( Type = 'CustInvc' ) AND ( BUILTIN.CF( Status ) IN ('CustInvc:A','CustInvc:B') AND TO_CHAR(trandate, 'mm') = TO_CHAR(sysdate, 'mm')
AND TO_CHAR(trandate, 'yyyy') = TO_CHAR(sysdate, 'yyyy') ) )
OR ( ( Type = 'CashSale' ) AND ( BUILTIN.CF( Status ) IN ('CashSale:C','CashSale:B') AND TO_CHAR(trandate, 'mm') = TO_CHAR(sysdate, 'mm')
AND TO_CHAR(trandate, 'yyyy') = TO_CHAR(sysdate, 'yyyy') ) )
OR ( ( Type = 'CustCred' ) AND ( BUILTIN.CF( Status ) IN ('CustCred:B','CustCred:A') AND TO_CHAR(trandate, 'mm') = TO_CHAR(sysdate, 'mm')
AND TO_CHAR(trandate, 'yyyy') = TO_CHAR(sysdate, 'yyyy') ) )
GROUP BY
Employee,
Type
)
,
Totals AS
(
SELECT
NULL AS RepName,
SUM ( CASE WHEN Type = 'Opprtnty' THEN ProjectedTotal ELSE 0 END ) AS Opportunity_Total,
SUM ( CASE WHEN Type = 'SalesOrd' THEN ForeignTotal ELSE 0 END ) AS Sales_Pending_Total,
SUM ( CASE WHEN Type = 'CustInvc' THEN ForeignTotal ELSE 0 END ) AS Invoiced,
SUM ( CASE WHEN Type = 'CashSale' THEN ForeignTotal ELSE 0 END ) AS Cash_Sale,
SUM ( CASE WHEN Type = 'CustCred' THEN ForeignTotal ELSE 0 END ) AS Credit_Memo,
NULL AS forecast
FROM
Transaction
WHERE
( ( Type = 'SalesOrd' ) AND ( BUILTIN.CF( Status ) IN ('SalesOrd:B','SalesOrd:A') AND TO_CHAR(shipdate, 'mm') = TO_CHAR(sysdate, 'mm')
AND TO_CHAR(shipdate, 'yyyy') = TO_CHAR(sysdate, 'yyyy') ) )
OR ( ( Type = 'Opprtnty' ) AND ( BUILTIN.CF( Status ) IN ('Opprtnty:A','Opprtnty:C') AND TO_CHAR(expectedclosedate, 'mm') = TO_CHAR(sysdate, 'mm')
AND TO_CHAR(expectedclosedate, 'yyyy') = TO_CHAR(sysdate, 'yyyy') ) )
OR ( ( Type = 'CustInvc' ) AND ( BUILTIN.CF( Status ) IN ('CustInvc:A','CustInvc:B') AND TO_CHAR(trandate, 'mm') = TO_CHAR(sysdate, 'mm')
AND TO_CHAR(trandate, 'yyyy') = TO_CHAR(sysdate, 'yyyy') ) )
OR ( ( Type = 'CashSale' ) AND ( BUILTIN.CF( Status ) IN ('CashSale:C','CashSale:B') AND TO_CHAR(trandate, 'mm') = TO_CHAR(sysdate, 'mm')
AND TO_CHAR(trandate, 'yyyy') = TO_CHAR(sysdate, 'yyyy') ) )
OR ( ( Type = 'CustCred' ) AND ( BUILTIN.CF( Status ) IN ('CustCred:B','CustCred:A') AND TO_CHAR(trandate, 'mm') = TO_CHAR(sysdate, 'mm')
AND TO_CHAR(trandate, 'yyyy') = TO_CHAR(sysdate, 'yyyy') ) )
)
SELECT
a.RepName,
a.Opportunity_Total,
a.Sales_Pending_Total,
a.Invoiced,
a.Cash_Sale,
a.Credit_Memo,
case when (a.Sales_Pending_Total + a.Invoiced + a.Cash_Sale + a.Credit_Memo) < Opportunity_Total
then Opportunity_Total*-1
else (a.Sales_Pending_Total + a.Invoiced + a.Cash_Sale + a.Credit_Memo) END as forecast
from(
SELECT
RepID,
( Employee.FirstName || ', ' || Employee.LastName ) AS RepName,
SUM ( CASE WHEN Type = 'Opprtnty' THEN ProjectedTotal ELSE 0 END ) AS Opportunity_Total,
SUM ( CASE WHEN Type = 'SalesOrd' THEN ForeignTotal ELSE 0 END ) AS Sales_Pending_Total,
SUM ( CASE WHEN Type = 'CustInvc' THEN ForeignTotal ELSE 0 END ) AS Invoiced,
SUM ( CASE WHEN Type = 'CashSale' THEN ForeignTotal ELSE 0 END ) AS Cash_Sale,
SUM ( CASE WHEN Type = 'CustCred' THEN ForeignTotal ELSE 0 END ) AS Credit_Memo,
FROM
SalesSummary
INNER JOIN Employee ON
( Employee.ID = SalesSummary.RepID )
WHERE
RepID IN ('17','24','-5','26')
GROUP BY
RepID,
( Employee.FirstName || ', ' || Employee.LastName )
ORDER BY
RepName
) a
UNION
SELECT
RepName,
Opportunity_Total,
Sales_Pending_Total,
Invoiced,
Cash_Sale,
Credit_Memo,
forecast
FROM
Totals
Related
Trying to get my head around this but I am stumped. Can I use an IIf with a HAVING statement or a CASE?
My current SQL is this:
SELECT dbo_forecast.mtl_part_part_nbr,
SUM(Round(dbo_forecast.forecast_qty)) AS FCST,
dbo_m8stacd_standards.whse_nbr,
dbo_m8stacd_standards.statn_cd,
dbo_m8stacd_standards.prty
INTO tblforecast77
FROM dbo_m8stacd_standards
INNER JOIN dbo_forecast
ON dbo_m8stacd_standards.part_nbr =
dbo_forecast.mtl_part_part_nbr
WHERE ( ( ( dbo_forecast.type ) = 11
OR ( dbo_forecast.type ) = 12 )
AND ( ( dbo_forecast.forecast_month ) = '01'
OR ( dbo_forecast.forecast_month ) = '02'
OR ( dbo_forecast.forecast_month ) = '03'
OR ( dbo_forecast.forecast_month ) = '04'
OR ( dbo_forecast.forecast_month ) = '05'
OR ( dbo_forecast.forecast_month ) = '06'
OR ( dbo_forecast.forecast_month ) = '07'
OR ( dbo_forecast.forecast_month ) = '08'
OR ( dbo_forecast.forecast_month ) = '09'
OR ( dbo_forecast.forecast_month ) = '10'
OR ( dbo_forecast.forecast_month ) = '11'
OR ( dbo_forecast.forecast_month ) = '12' ) )
GROUP BY dbo_forecast.mtl_part_part_nbr,
dbo_m8stacd_standards.whse_nbr,
dbo_m8stacd_standards.statn_cd,
dbo_m8stacd_standards.prty
HAVING ( ( ( dbo_forecast.mtl_part_part_nbr ) = "00104918" )
AND ( ( dbo_m8stacd_standards.whse_nbr ) = 77 )
AND ( ( dbo_m8stacd_standards.prty ) = "01"
OR ( dbo_m8stacd_standards.prty ) = "d" )
AND ( ( SUM(Round([dbo_forecast].[forecast_qty])) ) > 0 ) );
And returns this:
What I want to return is if there is a "D" in prty (for that part number) return the FCST for that, if there is not a prty (for that part number) D return the FCST for prty = "01"
edit: Sorry I should have worded this better. What I want is return one record. The prty=d record if it exists, otherwise the 01 record.
I have a view from the view need to fetch some result set for that purpose I have wrote following query.
So here the problem is stuff with xml is taking so much time any suggestions please.
;WITH CTE_transaction_type1 AS
(
SELECT case_summary_id,Primary_Payer, Physician,Generate_Bill,
CASE
WHEN Current_Payer IS NULL
THEN CASE
WHEN Resposible_Patient_Name IS NULL
AND PG_Patient_Name IS NULL
THEN 'PG:' + Patient_Last_Name + ',' + Patient_First_Name
WHEN Resposible_Patient_Name IS NULL
AND NULLIF(PG_Patient_Name,' ') IS NOT NULL
THEN 'SG:' + Patient_Last_Name + ',' + Patient_First_Name
ELSE Resposible_Patient_Name
END
ELSE
CASE
WHEN Current_Payer_Name IS NULL
THEN ''
ELSE Insurance_Type + Current_Payer_Name + IIF(Plan_Name IS NULL, '', ',' + Plan_Name)
END
END AS Responsible_Party_List
FROM [charts].[vw_billing_analysis]
WHERE sort_order = 0 AND transaction_type_id = 1
)
SELECT ba.Case_Summary_ID
,ba.date_of_surgery
,ba.Organization_ID
,ba.Organization_Name
,ba.Patient_Name
,ba.Patient_First_Name
,ba.Patient_Last_Name
,ba.MRN
,ba.Physician_ID
,ba.Physician
,ba.[PROCEDURE]
,ba.Current_Payer
,ba.Current_Payer_Name
,ba.Primary_Payer
,ba.Primary_Payer_ID
,ba.Insurance_Plan_ID
,ba.Insurance_Plan_Type
,ba.Plan_Name
,ba.Speciality_ID
,ba.Speciality_Name
,ba.Transaction_Responsible_Party_ID
,ba.Charge_ID
,ba.Charge_Procedure_ID
,ba.Patient_Insurance_ID
,ba.Insurance_Type
,ba.Resposible_Patient_Name
,ba.Received_From
,ba.Guarantor_Master_ID
,ba.PG_Patient_Name
,ba.Batch_Description
,ba.Period_Name
,ba.Unassigned_payment
,ba.Charge
,ba.Charge_Corr
,ba.Debit
,ba.Payments
,ba.WriteOff
,ba.Balance
,ba.Corrected_TF
,ba.Period_ID
,ba.Batch_ID
,ba.transaction_type_id
,STUFF((
SELECT '; ' + [Procedure]
FROM [charts].[vw_billing_analysis] vba
WHERE vba.case_summary_id = ba.case_summary_id
AND vba.transaction_type_id = 1
ORDER BY ba.sort_order
FOR XML PATH('')
,TYPE
).value('.', 'NVARCHAR(MAX)'), 1, 2, '') AS Procedure_List
,trty1.Primary_Payer AS Primary_Payer_List
,trty1.Responsible_Party_List
,trty1.Physician AS Physician_List
,ba.Allowed_Amount
,IIF(ba.insurance_contract_id IS NULL
OR ba.Insurance_Plan_Type = 'Self-Pay', NULL, iif(ba.procedure_type IS NOT NULL, round(ba.[allowed_amount] - (ba.[allowed_amount] * ba.procedure_discount / 100.0), 3), ba.[procedure_amount])) AS [Expected_Amount]
,ba.Procedure_Amount
,ba.Generate_Bill
,trty1.Generate_Bill AS Generate_Bill_Case
,ba.Actual_Payment
,ba.First_Bill_Date
FROM [charts].[vw_billing_analysis] ba
left join cte_transaction_type1 trty1
ON ba.Case_Summary_ID=trty1.Case_Summary_ID
WHERE ba.Organization_ID =52
AND
(
(
(
(
ba.Period_Id = ('999999999')
OR '999999999' = '999999999'
)
AND 0 = 1
)
AND (
(
ba.Batch_Id IN ('999999999')
OR '999999999' = '999999999'
)
AND 0 = 1
)
)
OR (
0 = 0
AND ba.date_of_surgery >= '2018-02-01'
AND ba.date_of_surgery <= '2021-03-03'
)
)
AND (
CASE
WHEN ba.Insurance_Plan_Type IS NULL
AND ba.Insurance_Plan_ID IS NULL
AND ba.Current_Payer IS NULL
THEN '-1'
ELSE ba.Insurance_Plan_Type_Id
END IN ('999999999')
OR '999999999' = '999999999'
)
AND (
ba.Current_Payer IN ('999999999')
OR '999999999' = '999999999'
)
AND (
ba.Speciality_ID IN ('999999999')
OR '999999999' = '999999999'
)
AND (
ba.Physician_ID IN ('999999999')
OR '999999999' = '999999999'
)
AND (
isnull(ba.Primary_Payer_ID, - 1) IN ('999999999')
OR '999999999' = '999999999'
)
AND (
ba.appointment_type_id IN ('999999999')
OR '999999999' = '999999999'
)
AND (
SELECT SUM(CASE
WHEN vba.transaction_type_id = 1
THEN balance
WHEN vba.transaction_type_id = 3
THEN - balance
END)
FROM [charts].[vw_billing_analysis] vba
WHERE vba.case_summary_id = ba.case_summary_id
) >= 0
ORDER BY ba.Date_Of_Surgery DESC
,ba.MRN DESC
,ba.Patient_Name ASC
,ba.upd_tr_sort ASC
,ba.Sort_Order ASC
When I execute this view I get this error:-
Conversion failed when converting date and/or time from character string
Please help me out what kind of mistake I'm making in this given query??*
SQL Query:
WITH CTE_aacd1 AS (
SELECT *
FROM (
SELECT LEAD_CO_MNE
,ACCOUNT_NO
,CLOSURE_TYPE
,DATE_TIME
,Rank() OVER (ORDER BY [DATE_TIME]) AS rank_
FROM [InsightSource].BS.AA_ACCOUNT_CLOSURE_DETAILS
) aat
WHERE aat.rank_ = 1
)
SELECT [Date].BusinessDate as [BusinessDate] , aa.LEAD_CO_MNE as LeadCompany , 'BS' as SourceSystem , concat('BS:' , com.FINANCIAL_MNE , ':' , cast(aa.[LINKED_APPL_ID] as nvarchar(50))) as [SourceAccountId] , concat('BS:' ,CO_CHK.COMPANY_MNE , ':' , CAST(isnull(A.[CO_CODE], aa.[CO_CODE]) as nvarchar(50))) as [SourceBranchId] , concat('BS:' , COM.CUSTOMER_MNEMONIC , ':' , cast(isnull(A.[CUSTOMER], aa.[CUSTOMER]) as nvarchar(50))) as [SourceCustomerId] , concat('BS:' , CO_CHK.COMPANY_MNE , ':' , cast(A.[ACCOUNT_OFFICER] as nvarchar(50))) as [SourceEmployeeId] , concat('BS:' , com.CUSTOMER_MNEMONIC , ':' , l.[#id]) as [SourceLimitId] --,A.[CATEGORY] as [sourceGLId] ,aa.[LINKED_APPL_ID] as [AccountNum]
,-1 * Rb.Debitbal as Balance ,-1 * rb.ForeignDebitBal as [ForeignCurrencyBal] ,'Loan' as [Category] ,A.[CURRENCY] as [Currency] ,-1 * rb.InterestAccrued as [InterestAccrued] ,rb.InterestRate as InterestRate ,rb.FixOrVAr ,rb.Rate_tier_type as RateType --,rb.InterestRateIndex ,rb.InterestRateVariance ,p.[#ID] as [ProductCode] ,P.DESCRIPTION as [ProductDesc] ,aa.PRODUCT_GROUP as [ProductType] ,aa.PRODUCT_GROUP as [T24ProductGroup] ,aa.[START_DATE] as [StartDate] ,isnull(aa.ORIG_CONTRACT_DATE, aa.[START_DATE]) OriginalStartDate ,case when a.INACTIV_MARKER = 'Y' then 'InActive' else AA.[ARR_STATUS] end as [StatusCode] ,a.[ACCOUNT_TITLE_1] as [StatementDesc] ,isnull(aacd.RENEWAL_DATE, aacd.MATURITY_DATE) as MaturityDate ,cast(aacd.MATURITY_DATE as date) as AmortMatureDate ,cast(aata.[AMOUNT] as decimal (28,4)) as OriginalLoanAmount ,cast(aata.[AMOUNT] as decimal (28,4)) as Authorized ,right(rtrim(Isnull(aacp.CHANGE_PERIOD, aata.TERM)), 1) as TermUnit ,try_convert(int,SUBSTRING( Isnull(aacp.CHANGE_PERIOD, aata.TERM), 1, len(isnull(aacp.CHANGE_PERIOD, aata.TERM))-1 )) as Term ,case when right(rtrim(Isnull(aacp.CHANGE_PERIOD, aata.TERM)), 1) = 'M' then try_convert(int,SUBSTRING(Isnull(aacp.CHANGE_PERIOD, aata.TERM), 1, len(Isnull(aacp.CHANGE_PERIOD, aata.TERM))-1 )) when right(rtrim(Isnull(aacp.CHANGE_PERIOD, aata.TERM)), 1) = 'D' then try_convert(int,round(try_convert(int,SUBSTRING(Isnull(aacp.CHANGE_PERIOD, aata.TERM), 1, len(Isnull(aacp.CHANGE_PERIOD, aata.TERM))-1 ))*(1/(365.25/12)) , 0)) when right(rtrim(Isnull(aacp.CHANGE_PERIOD, aata.TERM)), 1) = 'Y' then try_convert(int,round(try_convert(int,SUBSTRING( Isnull(aacp.CHANGE_PERIOD, aata.TERM), 1, len(Isnull(aacp.CHANGE_PERIOD, aata.TERM))-1 ))*12 , 0))
else NULL end as TermInMonths, case when right(rtrim(Isnull(aacp.CHANGE_PERIOD, aata.TERM)), 1) = 'M' then try_convert(int,round(try_convert(int,SUBSTRING( Isnull(aacp.CHANGE_PERIOD, aata.TERM), 1, len(Isnull(aacp.CHANGE_PERIOD, aata.TERM))-1 ))*30.44,0)) when right(rtrim(Isnull(aacp.CHANGE_PERIOD, aata.TERM)), 1) = 'D' then try_convert(int,SUBSTRING( Isnull(aacp.CHANGE_PERIOD, aata.TERM), 1, len(Isnull(aacp.CHANGE_PERIOD, aata.TERM))-1 )) when right(rtrim(Isnull(aacp.CHANGE_PERIOD, aata.TERM)), 1) = 'Y' then try_convert(int,round(try_convert(int,SUBSTRING( Isnull(aacp.CHANGE_PERIOD, aata.TERM), 1, len(Isnull(aacp.CHANGE_PERIOD, aata.TERM))-1 ))*365.25 , 0)) else NULL end as TermInDays ,aacd.[START_DATE] as DisburseDate ,case when aacd.ARR_AGE_STATUS = 'DEL' then 'Yes' else 'No' end as IsDelinquent ,del.DelinquentAmount ,del.LastDelinquentDate -- (!!! ERROR !!!),case when LastDelinquentDate is not null and isdate(del.LastDelinquentDate) = 1 then datediff( d, del.LastDelinquentDate, date.BusinessDate ) end as DelinquentDays ,case when (LastDelinquentDate is not null) and (TRY_CONVERT(DATE, del.LastDelinquentDate) IS NOT NULL) then datediff(d, TRY_CONVERT(DATE, del.LastDelinquentDate), [date].BusinessDate ) end as DelinquentDays ,aacd1.CLOSURE_TYPE as ReasonClosed ,cast(left('20' + aacd1.DATE_TIME, 8) as date) as ClosedDate ,-1 * rb.DebitBal as [AvailableFunds] ,left(arrschedule.Start_date, 8) as FirstPmtDate ,arrschedule.Calc_Amount as ScheduledPmtAmt ,case when payment_freq like '%e1M%' and payment_freq not like '%o%,%D%' then 'Monthly' when payment_freq like '%e1M%' and payment_freq like '%o%,%D%' then 'Twice a month' when payment_freq like '%e2M%' and payment_freq not like '%o%,%D%' then 'Every 2 month' when payment_freq like '%e2M%' and payment_freq like '%o%,%D%' then 'Twice every 2 month' when payment_freq like '%e1W%' or payment_freq like '%e7D%' then 'Weekly' when payment_freq like '%e2W%' or payment_freq like '%e14D%' then 'Bi-Weekly' else 'N/A' end as PmtFreq ,case when intfreq like '%e1M%' and intfreq not like '%o%,%D%' then 'Monthly' when intFreq like '%e1M%' and intfreq like '%o%,%D%' then 'Twice a month' when intFreq like '%e2M%' and intfreq not like '%o%,%D%' then 'Every 2 month' when intFreq like '%e2M%' and intfreq like '%o%,%D%' then 'Twice every 2 month' when payment_freq like '%e1W%' or payment_freq like '%e7D%' then 'Weekly' when payment_freq like '%e2W%' or payment_freq like '%e14D%' then 'Bi-Weekly' else 'N/A' end as InterestPaidFreq , arrschedule.payment_type as PmtCalcMethod ,'BSAA_Lending' as SystemSource FROM [InsightSource].[BS].[AA_ARRANGEMENT] aa LEFT JOIN [InsightSource].[BS].[COMPANY] COM ON COM.MNEMONIC = AA.BRANCH_CO_MNE LEFT JOIN [InsightSource].[BS].[COMPANY_CHECK_Company_Mne] CO_CHK ON CO_CHK.[#ID] = 'MASTER' and CO_CHK.[Sequence] = 1 LEFT JOIN [InsightSource].[BS].[ACCOUNT] a ON a.LEAD_CO_MNE = COM.FINANCIAL_MNE AND A.[#ID] = aa.LINKED_APPL_ID LEFT JOIN [InsightSource].BS.LIMIT l ON a.CUSTOMER +'.' + RIGHT ( '0000' + a.LIMIT_REF , 10) = l.[#ID] AND l.LEAD_CO_MNE = COM.CUSTOMER_MNEMONIC LEFT JOIN (Select del1.[#id], DEL1.ARRANGEMENT_ID, Del1.LEAD_CO_MNE, del1.LastDelinquentDate, SUM(cast(bd.OS_TOTAL_AMOUNT as decimal (28,4))) as DelinquentAmount from
(select aad.[#id], AAD.LEAD_CO_MNE, AAD.ARRANGEMENT_ID, min(billpay.Bill_Pay_date) as LastDelinquentDate, max(billpay.Bill_Pay_date) as MaxDelinquentDate
from
( select [#id], [LEAD_CO_MNE], ARR_AGE_STATUS, [#ID] AS ARRANGEMENT_ID, BILL_PAY_DATE from [InsightSource].BS.AA_ACCOUNT_DETAILS where ARR_AGE_STATUS in ('NAB', 'DEL')) aad join
( select * from [InsightSource].BS.AA_ACCOUNT_DETAILS_Bill_Pay_date where Aging_Status
= 'DEL' or bill_status = 'Aging') billpay on aad.[#id] = billpay.[#id] and aad.[LEAD_CO_MNE] = billpay.[LEAD_CO_MNE]
group by aad.[#id], AAD.ARRANGEMENT_ID, aad.[LEAD_CO_MNE]
) Del1
join
[InsightSource].BS.AA_BILL_DETAILS bd on del1.LEAD_CO_MNE = bd.LEAD_CO_MNE AND bd.[ARRANGEMENT_ID] = DEL1.ARRANGEMENT_ID --and del1.MaxDelinquentDate = bd.actual_pay_date Group by del1.[#id], DEL1.ARRANGEMENT_ID, del1.[LEAD_CO_MNE], del1.LastDelinquentDate )del ON AA.LEAD_CO_MNE = DEL.LEAD_CO_MNE AND AA.[#ID] = DEL.ARRANGEMENT_ID LEFT JOIN (select LEAD_CO_MNE, ID_COMP_1, replace (max(CHANGE_PERIOD) , 'R_BIRTH + ' , '') as CHANGE_PERIOD from [InsightSource].BS.AA_ARR_CHANGE_PRODUCT arr1 where ID_COMP_3 = (select MAX (ID_COMP_3) from [InsightSource].BS.AA_ARR_CHANGE_PRODUCT arr2 where arr1.ID_COMP_1 = arr2.ID_COMP_1 ) group by ID_COMP_1, LEAD_CO_MNE ) aacp ON COM.FINANCIAL_MNE = aacp.LEAD_CO_MNE AND AA.[#ID] = aacp.ID_Comp_1 LEFT JOIN CTE_aacd1 aacd1 ON aacd1.LEAD_CO_MNE = COM.CUSTOMER_MNEMONIC AND aacd1.ACCOUNT_NO = A.[#ID] LEFT JOIN ( SELECT * FROM ( SELECT [#ID]
,[LEAD_CO_MNE]
,PRODUCT
,PRODUCT_STATUS
,Rank() OVER (partition by [#id]
ORDER BY [PROD_EFF_DATE]
) AS rank_
FROM [InsightSource].BS.AA_ARRANGEMENT_PRODUCT
where [PRODUCT_STATUS] = 'CURRENT'
) aap1 WHERE aap1.rank_ = 1 ) aap ON aa.[#ID] = aap.[#ID] AND AAP.[LEAD_CO_MNE] = COM.[FINANCIAL_MNE]
LEFT JOIN [InsightSource].BS.AA_PRODUCT p ON CASE WHEN COM.SPCL_FIN_FILE IS NULL THEN COM.DEFAULT_FINAN_MNE ELSE COM.SPCL_FIN_MNE END = P.BRANCH_CO_MNE AND AAP.PRODUCT = P.[#ID] LEFT JOIN [InsightSource].BS.AA_ACCOUNT_DETAILS aacd ON aacd.[LEAD_CO_MNE] = COM.FINANCIAL_MNE AND aacd.[#ID] = aa.[#ID] LEFT JOIN ( select ps.[#id] ,ps.LEAD_CO_MNE, ps.ID_Comp_1 , ps.Base_date, sfi.Calc_Amount, sf.Actual_amt, sf.payment_freq , sf.payment_type , ps.Start_date, SFI.DUE_FREQ as intFreq ,case when sf.payment_freq like '%e1M%' and sf.payment_freq not like '%o%,%D%' then 1
when sf.payment_freq like '%e1M%' and sf.payment_freq like '%o%,%D%' then 2
when sf.payment_freq like '%e2M%' and sf.payment_freq like '%o%,%D%' then 1
when sf.payment_freq like '%e1W%' then 4
when sf.payment_freq like '%e2W%' then 2
end as NumPmtInOneMonth from [InsightSource].bs.AA_ARR_PAYMENT_SCHEDULE ps join [InsightSource].bs.AA_ARR_PAYMENT_SCHEDULE_payment_freq sf on
ps.[#id] = sf.[#id] and ps.[LEAD_CO_MNE] = sf.[LEAD_CO_MNE] and sequence = 1 left join [InsightSource].bs.AA_ARR_PAYMENT_SCHEDULE_payment_freq_property sfi on ps.[#id] = sfi.[#id] and ps.[lead_co_mne] = sfi.[lead_co_mne] and sfi.property = 'INTEREST' and sfi.MVsequence = 1 and sfi.sequence = 1 where ps.id_comp_3 = (select MAX (id_comp_3) from [InsightSource].BS.AA_ARR_PAYMENT_SCHEDULE arr2 where ps.ID_COMP_1 = arr2.ID_COMP_1 ) and sfi.Calc_Amount is not null group by ps.LEAD_CO_MNE,ps.[#id] , ps.ID_Comp_1, ps.Base_date, sfi.Calc_Amount, sf.Actual_amt, sf.payment_freq , sf.payment_type , ps.Start_date ,SFI.DUE_FREQ, [bill_produced] ) arrSchedule ON aa.LEAD_CO_MNE = arrSchedule.LEAD_CO_MNE AND AA.[#ID] = arrSchedule.ID_Comp_1 LEFT JOIN (select LEAD_CO_MNE,max(REVOLVING) as REVOLVING, max(TERM) as TERM, max(AMOUNT) as amount, ID_COMP_1 from [InsightSource].BS.AA_ARR_TERM_AMOUNT arr1 where ID_COMP_3 = (select MAX (ID_COMP_3) from [InsightSource].BS.AA_ARR_TERM_AMOUNT arr2 where arr1.ID_COMP_1 = arr2.ID_COMP_1 ) group by ID_COMP_1,LEAD_CO_MNE ) aata ON COM.FINANCIAL_MNE = aata.LEAD_CO_MNE AND AA.[#ID] = aata.ID_Comp_1 LEFT JOIN [v_sourceAccountBSAA_RatesandBalances] rb ON rb.[Linked_appl_id] = aa.LINKED_APPL_ID and rb.Lead_co_mne = aa.LEAD_CO_MNE CROSS JOIN [InsightStaging].[dbo].[v_sourceDate] as [Date] WHERE aa.PRODUCT_LINE = 'LENDING' and aa.[LINKED_APPL_ID] is not null
Why does the following query give me the following error if I am including the group by:
ORA-00937: not a single-group group function
select petf.element_name en,
--tm.i,
--sum(xxpay_util.safe_to_number(prrv.result_value)) s
nvl(max(decode(tm.i, 1, sum(xxpay_util.safe_to_number(prrv.result_value)), null)), 0) e1,
nvl(max(decode(tm.i, 2, sum(xxpay_util.safe_to_number(prrv.result_value)), null)), 0) e2
from (
select rownum i,
sub.*
from (
select trunc(decode(pbg.legislation_code, 'ZA', ptp.pay_advice_date, ptp.regular_payment_date), 'MM') month_date,
min(ptp.start_date) real_month_start,
max(ptp.end_date) real_month_end
from per_business_groups pbg,
per_time_periods ptp
where pbg.business_group_id = :P_BG_ID
and ptp.payroll_id = :PAYROLL_ID
and decode(pbg.legislation_code, 'ZA', ptp.pay_advice_date, trunc(ptp.regular_payment_date, 'MM')) between xxpay_util.get_tax_year(pbg.legislation_code, :P_TAX_YEAR, 'start')
and xxpay_util.get_tax_year(pbg.legislation_code, :P_TAX_YEAR, 'end')
group by trunc(decode(pbg.legislation_code, 'ZA', ptp.pay_advice_date, ptp.regular_payment_date), 'MM')
order by 1
) sub
) tm,
pay_element_classifications pec,
pay_element_types_f petf,
pay_input_values_f pivf,
pay_run_result_values prrv,
pay_run_results prr,
pay_assignment_actions paa,
pay_payroll_actions ppa,
per_time_periods ptp
where instr('|' || :PRIMARY_CLASS_IDS || '|', '|' || to_char(nvl(pec.parent_classification_id, -6969)) || '|') > 0
and
(
petf.classification_id = pec.classification_id
or instr('|' || :PRIMARY_CLASS_IDS || '|', '|' || to_char(nvl(petf.classification_id, -6969)) || '|') > 0
)
and tm.real_month_end between petf.effective_start_date and petf.effective_end_date
and pivf.element_type_id = petf.element_type_id
and pivf.name = 'Pay Value'
and prrv.input_value_id = pivf.input_value_id
and nvl(prrv.result_value, '0') <> '0'
and prr.run_result_id = prrv.run_result_id
and prr.status in ('P', 'PA') -- RUN_RESULT_STATUS lookup
and prr.element_type_id = petf.element_type_id
and paa.assignment_action_id = prr.assignment_action_id
and paa.action_status = 'C'
and paa.assignment_id = :ASSIGNMENT_ID
and ppa.payroll_action_id = paa.payroll_action_id
and ppa.action_status = 'C'
and ppa.action_type in ('B', 'F', 'G', 'I', 'O', 'Q', 'R', 'V', 'L') -- = 'R'
and ptp.time_period_id = ppa.time_period_id
and ptp.start_date >= tm.real_month_start
and ptp.end_date <= tm.real_month_end
group by petf.element_name
-- ,tm.i
:PRIMARY_CLASS_IDS is a string such as 105|107|112|113, listing the primary classification id's.
Fixed it by putting the whole query in another sub query:
select sub2.element_name,
max(decode(sub2.i, 11, sub2.result, null)) e11,
max(decode(sub2.i, 12, sub2.result, null)) e12
from (
select petf.element_name,
tm.i,
sum(xxpay_util.safe_to_number(prrv.result_value)) result
from (
select rownum i,
sub.*
from (
select trunc(decode(pbg.legislation_code, 'ZA', ptp.pay_advice_date, ptp.regular_payment_date), 'MM') month_date,
min(ptp.start_date) real_month_start,
max(ptp.end_date) real_month_end
from per_business_groups pbg,
per_time_periods ptp
where pbg.business_group_id = :P_BG_ID
and ptp.payroll_id = :PAYROLL_ID
and decode(pbg.legislation_code, 'ZA', ptp.pay_advice_date, trunc(ptp.regular_payment_date, 'MM')) between xxpay_util.get_tax_year(pbg.legislation_code, :P_TAX_YEAR, 'start')
and xxpay_util.get_tax_year(pbg.legislation_code, :P_TAX_YEAR, 'end')
group by trunc(decode(pbg.legislation_code, 'ZA', ptp.pay_advice_date, ptp.regular_payment_date), 'MM')
order by 1
) sub
) tm,
(
select distinct petf.element_type_id
from pay_element_classifications pec,
pay_element_types_f petf
where instr('|' || :PRIMARY_CLASS_IDS || '|', '|' || to_char(nvl(pec.parent_classification_id, -6969)) || '|') > 0
and
(
petf.classification_id = pec.classification_id
or instr('|' || :PRIMARY_CLASS_IDS || '|', '|' || to_char(nvl(petf.classification_id, -6969)) || '|') > 0
)
) ele,
pay_element_types_f petf,
pay_input_values_f pivf,
pay_run_result_values prrv,
pay_run_results prr,
pay_assignment_actions paa,
pay_payroll_actions ppa
where petf.element_type_id = ele.element_type_id
and tm.real_month_end between petf.effective_start_date and petf.effective_end_date
and pivf.element_type_id = petf.element_type_id
and pivf.name = 'Pay Value'
and prrv.input_value_id = pivf.input_value_id
and nvl(prrv.result_value, '0') <> '0'
and prr.run_result_id = prrv.run_result_id
and prr.status in ('P', 'PA') -- RUN_RESULT_STATUS lookup
and prr.element_type_id = petf.element_type_id
and paa.assignment_action_id = prr.assignment_action_id
and paa.action_status = 'C'
and paa.assignment_id = :ASSIGNMENT_ID
and ppa.payroll_action_id = paa.payroll_action_id
and ppa.action_status = 'C'
and ppa.action_type in ('B', 'F', 'G', 'I', 'O', 'Q', 'R', 'V', 'L') -- = 'R'
and ppa.effective_date between tm.real_month_start and tm.real_month_end
and petf.element_name in ('ZA_Tax_Costing', 'ZA_UIF_Employee_Contribution')
group by petf.element_name,
tm.i
) sub2
group by sub2.element_name
I beg your pardon for such a lengthy query, but I am in desperate need of help.
When I run the query below, I get daily data. But I want monthly data, using LASTDAY,
SUM, GROUP BY function.
For instance, if I pick '20130501' in #startDt# and '20130701' in #endDt#, it should give me 3 rows of accumulated results; May, June and July. Can anyone help?
SELECT X.*
FROM
(
SELECT
(CASE
WHEN DAY.DAY = 'SUM' THEN DAY.DAY
ELSE TO_CHAR (TO_DATE (DAY.DAY, 'YYYY-MM-DD'), 'YYYYMMDD')
END
) AS DAY,
DAY.WEEK,
MNOT.SUM_STD_CNT AS MNOT_CNT,
RSC.MOVIE_500K AS MOVIE_500K_CNT,
RSC.MOVIE_1M AS MOVIE_1M_CNT,
RSC.MOVIE AS MOVIE_CNT,
RSC.EXAM AS EXAM_CNT,
RSC.WEB AS WEB_CNT,
RSC.IMG AS IMG_CNT,
RSC.INTERRAC AS INTERRACTIVE_CNT,
RSC.DOC AS DOC_CNT,
MNOT.SUM_STD_CNT + RSC.MOVIE_500K + RSC.MOVIE_1M + RSC.MOVIE + RSC.EXAM + RSC.WEB + RSC.IMG + RSC.INTERRAC + RSC.DOC TOT_CNT
FROM
/* DATES */
(SELECT
TO_CHAR (TO_DATE (#startDt#,'YYYY-MM-DD')+LEVEL- 1, 'YYYYMMDD') AS DAY
FROM DUAL
CONNECT BY TO_DATE(#startDt#, 'YYYY-MM-DD') + LEVEL - 1 <![CDATA[<=]]> TO_DATE(#endDt#, 'YYYY-MM-DD')
UNION ALL
SELECT 'SUM', '' FROM DUAL
) DAY LEFT OUTER JOIN
/* RESOURCE */
(
SELECT
NVL(DT_G.COMM_DT, 'SUM') COMM_DT
,NVL(SUM(DT_G.MOVIE_500K), 0) AS MOVIE_500K
,NVL(SUM(DT_G.MOVIE_1M), 0) AS MOVIE_1M
,NVL(SUM(DT_G.MOVIE), 0) AS MOVIE
,NVL(SUM(DT_G.EXAM), 0) AS EXAM
,NVL(SUM(DT_G.DOC), 0) AS DOC
,NVL(SUM(DT_G.IMG), 0) AS IMG
,NVL(SUM(DT_G.WEB), 0) AS WEB
,NVL(SUM(DT_G.INTERRAC), 0) AS INTERRAC
FROM
(
SELECT
COMM_DT
, CASE SUMT.RSC_TP_DSCD WHEN 'RTP10' THEN SUMT.SUM_500K END MOVIE_500K
, CASE SUMT.RSC_TP_DSCD WHEN 'RTP10' THEN SUMT.SUM_1M END AS MOVIE_1M
, CASE SUMT.RSC_TP_DSCD WHEN 'RTP10' THEN SUMT.SUM_500K+SUMT.SUM_1M END AS MOVIE
, CASE SUMT.RSC_TP_DSCD WHEN 'RTP11' THEN SUMT.SUM_STD_CNT END AS EXAM
, CASE SUMT.RSC_TP_DSCD WHEN 'RTP12' THEN SUMT.SUM_STD_CNT END AS DOC
, CASE SUMT.RSC_TP_DSCD WHEN 'RTP13' THEN SUMT.SUM_STD_CNT END AS IMG
, CASE SUMT.RSC_TP_DSCD WHEN 'RTP14' THEN SUMT.SUM_STD_CNT END AS WEB
, CASE SUMT.RSC_TP_DSCD WHEN 'RTP01' THEN SUMT.SUM_STD_CNT END AS INTERRAC
FROM (
SELECT RSC_TP_DSCD, SUM(STDY_CNT) AS SUM_STD_CNT, SUM(MOVIE_STDY_CNT_N1M) AS SUM_1M, SUM(MOVIE_STDY_CNT_N500K) AS SUM_500K, COMM_DT
FROM (
SELECT RSC_SNO, STDY_CNT, MOVIE_STDY_CNT_N1M, MOVIE_STDY_CNT_N500K, COMM_DT
FROM LRMS.V_EBSM_PKG_RSC_COMM_CNT
WHERE PKG_SNO = 0 AND RSC_SNO != 0
AND COMM_DT BETWEEN TO_CHAR(TO_DATE(#startDt#, 'YYYY-MM-DD'), 'YYYYMMDD') AND TO_CHAR(TO_DATE(#endDt#, 'YYYY-MM-DD'), 'YYYYMMDD')
) CNT
LEFT OUTER JOIN LRMS.V_LRRM_RSC RSC ON CNT.RSC_SNO = RSC.RSC_SNO
GROUP BY RSC_TP_DSCD, COMM_DT
) SUMT
) DT_G
GROUP BY ROLLUP(DT_G.COMM_DT)
) RSC ON DAY.DAY = RSC.COMM_DT
LEFT OUTER JOIN
(
SELECT NVL(SUM(STDY_CNT), 0) AS SUM_STD_CNT, NVL(COMM_DT, 'SUM') COMM_DT
FROM LRMS.V_EBSM_PKG_RSC_COMM_CNT
WHERE PKG_SNO != 0 AND RSC_SNO = 0
AND COMM_DT BETWEEN TO_CHAR(TO_DATE(#startDt#, 'YYYY-MM-DD'), 'YYYYMMDD') AND TO_CHAR(TO_DATE(#endDt#, 'YYYY-MM-DD'), 'YYYYMMDD')
GROUP BY ROLLUP(COMM_DT)
) MNOT ON DAY.DAY = MNOT.COMM_DT
) X
WHERE 1=1
and X.TOT_CNT IS NOT NULL
you can do something like
SELECT DATENAME(MONTH , DAY) , SUM(COLUMN1) , SUM(COLUMN2) ..
FROM (YOURQUERY) AS A
GROUP BY DATENAME(MONTH , DAY)
I think this will help you .