Cant able to create view with following snowflake query - snowflake-cloud-data-platform

Needs to create view with below columns. Need to understand how to create view using with clause inside the query.
create
or replace view TEST_RRX.DW_RRX.V_SIL_RRX_PTS_BusinessLocation_Dim(
--ROW_WID,
--ADDRESS_TYPE,
BUSN_LOC_NAME,
BUSN_LOC_NUM,
BUSN_LOC_TYPE,
ST_ADDRESS1,
ST_ADDRESS2,
CITY_NAME,
POSTAL_CODE,
STATE_CODE,
COUNTRY_CODE,
ACTIVE_FLG,
CREATED_BY_WID,
CHANGED_BY_WID,
CREATED_ON_DT,
CHANGED_ON_DT,
AUX1_CHANGED_ON_DT,
AUX2_CHANGED_ON_DT,
AUX3_CHANGED_ON_DT,
AUX4_CHANGED_ON_DT,
SRC_EFF_FROM_DT,
SRC_EFF_TO_DT,
EFFECTIVE_FROM_DT,
EFFECTIVE_TO_DT,
DELETE_FLG,
CURRENT_FLG,
W_INSERT_DT,
W_UPDATE_DT,
DATASOURCE_NUM_ID,
--ETL_PROC_WID,
INTEGRATION_ID,
--TENANT_ID,
--X_CUSTOM,
--GEO_COUNTRY_WID,
--GEO_WID,
UPD_FLG
) as WITH CODE AS (
SELECT
W_CODE_D.MASTER_CODE AS MASTER_CODE,
W_CODE_D.MASTER_VALUE AS MASTER_VALUE,
W_CODE_D.SOURCE_CODE AS SOURCE_CODE,
W_CODE_D.DATASOURCE_NUM_ID AS DATASOURCE_NUM_ID,
W_CODE_D.SOURCE_CODE_1 as SOURCE_CODE_1,
W_CODE_D.SOURCE_CODE_2 as SOURCE_CODE_2,
W_CODE_D.SOURCE_NAME_1 as SOURCE_NAME_1,
W_CODE_D.CATEGORY
FROM
W_CODE_D
WHERE
W_CODE_D.LANGUAGE_CODE = 'E'
),
USER_TAB as (
SELECT
LOOKUP_TABLE.ROW_WID as ROW_WID,
LOOKUP_TABLE.DATASOURCE_NUM_ID as DATASOURCE_NUM_ID,
LOOKUP_TABLE.INTEGRATION_ID as INTEGRATION_ID,
LOOKUP_TABLE.EFFECTIVE_FROM_DT as EFFECTIVE_FROM_DT,
LOOKUP_TABLE.EFFECTIVE_TO_DT as EFFECTIVE_TO_DT
FROM
DW_RRX.W_USER_D LOOKUP_TABLE
),
BUSN_LOCATION as (
SELECT
sq.BUSN_LOC_NAME,
sq.BUSN_LOC_NUM,
sq.BUSN_LOC_TYPE,
sq.ST_ADDRESS1,
sq.ST_ADDRESS2,
case when CITY.MASTER_VALUE is null then (
case when sq.CITY_NAME is null
OR LENGTH(sq.CITY_NAME) = 0
OR REGEXP_INSTR(sq.CITY_NAME, ' ')> 0 then 'Unspecified' else sq.CITY_NAME end
) else CITY.MASTER_VALUE end as city_name,
sq.POSTAL_CODE,
case when STATE.MASTER_CODE is null then (
case when sq.STATE_CODE is null
OR LENGTH(sq.STATE_CODE) = 0
OR REGEXP_INSTR(sq.STATE_CODE, ' ')> 0 then 'Unspecified' else sq.STATE_CODE end
) else STATE.MASTER_CODE end as STATE_CODE,
case when COUNTRY.MASTER_CODE is null then (
case when sq.COUNTRY_CODE is null
OR LENGTH(sq.COUNTRY_CODE) = 0
OR REGEXP_INSTR(sq.COUNTRY_CODE, ' ')> 0 then 'Unspecified' else sq.COUNTRY_CODE end
) else COUNTRY.MASTER_VALUE end as COUNTRY_CODE,
'Y' as ACTIVE_FLG,
CREATED_BY.ROW_WID AS CREATED_BY_WID,
CHANGED_BY.ROW_WID AS CREATED_BY_WID,
sq.AUX1_CHANGED_ON_DT,
sq.AUX2_CHANGED_ON_DT,
sq.AUX3_CHANGED_ON_DT,
sq.AUX4_CHANGED_ON_DT,
sq.SRC_EFF_FROM_DT,
sq.SRC_EFF_TO_DT,
case when W_BUSN_LOCATION_D.INTEGRATION_ID is null then current_date else W_BUSN_LOCATION_D.W_INSERT_DT end as EFFECTIVE_FROM_DT,
TO_DATE('01013714', 'DDMMYYYY') as EFFECTIVE_TO_DT,
'N' As DELETE_FLG,
'Y' AS CURRENT_FLG,
case when W_BUSN_LOCATION_D.INTEGRATION_ID is null then current_date else W_BUSN_LOCATION_D.W_INSERT_DT end as W_INSERT_DT,
W_BUSN_LOCATION_D.W_UPDATE_DT as current_date,
sq.DATASOURCE_NUM_ID,
--sq.ETL_PROC_WID,
sq.INTEGRATION_ID,
CASE WHEN (
SELECT
ETL_PROC_WID
FROM
TEST_RRX.DW_RRX.W_PARAM_G
WHERE
ROW_WID = 1
) = W_BUSN_LOCATION_D.ETL_PROC_WID THEN 'X' WHEN W_BUSN_LOCATION_D.INTEGRATION_ID IS NULL THEN 'I' WHEN W_BUSN_LOCATION_D.INTEGRATION_ID IS NOT NULL
AND (
sq.CHANGED_ON_DT <> W_BUSN_LOCATION_D.CHANGED_ON_DT
OR sq.AUX1_CHANGED_ON_DT <> W_BUSN_LOCATION_D.AUX1_CHANGED_ON_DT
OR sq.AUX2_CHANGED_ON_DT <> W_BUSN_LOCATION_D.AUX2_CHANGED_ON_DT
OR sq.AUX3_CHANGED_ON_DT <> W_BUSN_LOCATION_D.AUX3_CHANGED_ON_DT
OR sq.AUX4_CHANGED_ON_DT <> W_BUSN_LOCATION_D.AUX4_CHANGED_ON_DT
) THEN 'U' END as UPD_FLG
FROM
DW_RRX.W_BUSN_LOCATION_DS sq
LEFT OUTER JOIN CODE COUNTRY ON COUNTRY.SOURCE_CODE = sq.country_code
AND COUNTRY.DATASOURCE_NUM_ID = sq.DATASOURCE_NUM_ID
AND COUNTRY.CATEGORY = 'COUNTRY'
LEFT OUTER JOIN CODE CITY ON CITY.SOURCE_CODE_1 = sq.country_code
AND CITY.DATASOURCE_NUM_ID = sq.DATASOURCE_NUM_ID
AND CITY.SOURCE_CODE_2 = sq.STATE_CODE
AND CITY.SOURCE_NAME_1 = sq.CITY_NAME
AND CITY.CATEGORY = 'CITY'
LEFT OUTER JOIN CODE STATE ON STATE.DATASOURCE_NUM_ID = sq.DATASOURCE_NUM_ID
AND STATE.CATEGORY = 'STATE'
LEFT OUTER JOIN USER_TAB CREATED_BY ON sq.DATASOURCE_NUM_ID = CREATED_BY.DATASOURCE_NUM_ID
AND CREATED_BY.INTEGRATION_ID = sq.CREATED_BY_ID
and CREATED_BY.EFFECTIVE_FROM_DT <= sq.CREATED_ON_DT
and CREATED_BY.EFFECTIVE_TO_DT >= sq.CREATED_ON_DT
LEFT OUTER JOIN USER_TAB CHANGED_BY ON sq.DATASOURCE_NUM_ID = CHANGED_BY.DATASOURCE_NUM_ID
AND CHANGED_BY.INTEGRATION_ID = sq.CHANGED_BY_ID
and CHANGED_BY.EFFECTIVE_FROM_DT <= sq.CHANGED_ON_DT
and CHANGED_BY.EFFECTIVE_TO_DT >= sq.CHANGED_ON_DT
LEFT OUTER JOIN W_BUSN_LOCATION_D ON sq.INTEGRATION_ID = W_BUSN_LOCATION_D.INTEGRATION_ID
AND sq.DATASOURCE_NUM_ID = W_BUSN_LOCATION_D.DATASOURCE_NUM_ID
)
SELECT
*
FROM
BUSN_LOCATION
WHERE
UPD_FLG <> 'X'
Getting SQL compilation error: Invalid column definition list
Needs to create view with above columns

Related

Case When with Count inside an ON clause of a JOIN

Inside the JOIN (BB_VENDASDOCUMENTOS VD), I need to choose if VD.ENTRADASAIDA will be 'S' or 'E', what I actually need is, if there is at least one BB_VENDASDOCUMENTOS where ENTRADASAIDA = 'S', use 'S', else 'N'
I've tried to do a CASE WHEN counting the numer of VD.ENTRADASAIDA = 'S', if there is more then 0, It will use 'S', else 'N', but I'm getting an error that and aggregate cannot appear in an ON clause...
SELECT
CASE WHEN CENTROCUSTO.DESCRICAO IS NOT NULL THEN CENTROCUSTO.DESCRICAO + '|' ELSE '' END AS [text()]
FROM BB_PNRACCOUNTINGS ACC1
JOIN BB_VENDASDOCUMENTOS VD
ON ( VD.ACCOUNTING = ACC1.HANDLE
AND VD.ENTRADASAIDA = CASE WHEN count(case when VD.ENTRADASAIDA = 'S' THEN 1 ELSE NULL END ) > 0 THEN 'S' ELSE 'E' END
AND VD.PESSOA = ACC1.BB_CLIENTE
AND ( ( VD.CANCELADO = 'N' ) OR (VD.CANCELADO IS NULL) ) )
LEFT JOIN BB_CLIENTECC CENTROCUSTO
ON (CENTROCUSTO.Handle = VD.CENTRODECUSTO)
WHERE CENTROCUSTO.DESCRICAO IS NOT NULL
You will need to scan the table twice. Once to mark each group with a S or E and then to gather only the records that match the condition. I would do this by joining on a subquery and then join again on the condition. I am not sure the syntax below is 100% correct, however, the basic concept is there.
;WITH BB_VENDASDOCUMENTOSCalc AS
(
SELECT ACCOUNTING,PESSOA,
ENTRADASAIDACalc = count(case when ENTRADASAIDA = 'S' THEN 1 ELSE NULL END ) > 0 THEN 'S' ELSE 'E' END
FROM
BB_VENDASDOCUMENTOS
WHERE
(CANCELADO='N' OR CANCELADO IS NULL)
GROUP BY
ACCOUNTING,
PESSOA
)
SELECT
CASE WHEN CENTROCUSTO.DESCRICAO IS NOT NULL THEN CENTROCUSTO.DESCRICAO + '|' ELSE '' END AS [text()]
FROM BB_PNRACCOUNTINGS ACC1
JOIN BB_VENDASDOCUMENTOSCalc VD1 ON VD1.ACCOUNTING = ACC1.HANDLE AND VD1.PESSOA = ACC1.BB_CLIENTE
JOIN BB_VENDASDOCUMENTO VD ON VD.ACCOUNTING = ACC1.HANDLE AND VD.PESSOA = ACC1.BB_CLIENTE AND VD.ENTRADASAIDA = VD1.ENTRADASAIDACalc
LEFT JOIN BB_CLIENTECC CENTROCUSTO
ON (CENTROCUSTO.Handle = VD.CENTRODECUSTO)
WHERE CENTROCUSTO.DESCRICAO IS NOT NULL

Bad bind variables in oracle stored procedure

I am totally new to stored procedures. I have a query and I wanna use it for a web service. I am going to use Nhibernate. I have tried couple of procedures and worked well. But this one giving me problems. I tried to compile the stored procedure but giving me errors.
create or replace
PROCEDURE GET_RSM_LIFE_AGENT_DUES (p_recordset OUT SYS_REFCURSOR, :Year IN number, :Month IN number, :Branch IN number, :Agency IN number) AS
BEGIN
OPEN p_recordset for
select :Year as required_year, :Month as required_month,
case when pmagt = 0 then D.branch_code else E.branch_code end as branch_code,
case when pmagt = 0 then D.branch_name else E.branch_name end as branch_name,
case when pmagt = 0 then D.region else E.region end as region,
pmagt as agency,
status || ' ' || int || ' ' || name as agent_name,
pmpol as policy_no,
pmcom as commence_date,
pmtrm as term,
pmmod as policy_mode,
case WHEN pmtbl not in (51,22,74,75,76) and ((:Year - SUBSTR (pmcom,1,4)) * 12 + to_number(:Month) - SUBSTR (pmcom,-4,2)) < 12 then 'FYR'
WHEN pmtbl not in (51,22,74,75,76) and ((:Year - SUBSTR (pmcom,1,4)) * 12 + to_number(:Month) - SUBSTR (pmcom,-4,2)) >= 12 then 'Renewal' else '' end as premium_type,
case when llprm is not null and pmprm < llprm then llprm else pmprm end as due_Premium,
case when llprm is not null then llprm else 0 end as due_paid_premium
FROM lphs.premast A left outer join lclm.ledger B on (A.pmpol = B.llpol) and (to_number(:Year || :Month) = lldue)
left outer join agent.agent C on (A.pmagt = C.agency)
left outer join BAU.SLIC_BRANCH_LIST D on (A.pmobr = D.csp_code)
left outer join BAU.SLIC_BRANCH_LIST E on (C.branch = E.csp_code)
WHERE add_months(to_date(PMCOM,'YYYYMMDD'),PMTRM*12) >= add_months( to_date(:Year || :Month || 01 ,'YYYYMMDD'),1)
and to_date(pmcom,'yyyymmdd') < to_date(:Year || :Month || 01 ,'YYYYMMDD')
and pmmod <> 5
and stid in ('Ag' , 'ME', 'Or')
and case when to_date(pmcom,'yyyymmdd') >= to_date(:Year || :Month || 01 ,'YYYYMMDD') then 'N'
when pmmod = 4 then 'Y'
when pmmod = 3 and remainder ( abs( to_number ( substr (pmcom, 5,2) ) - to_number ( :Month ) ) , 3 ) =0 then 'Y'
when pmmod = 2 and remainder ( abs( to_number ( substr (pmcom, 5,2) ) - to_number ( :Month ) ) , 6 ) =0 then 'Y'
when pmmod = 1 and remainder ( abs( to_number ( substr (pmcom, 5,2) ) - to_number ( :Month ) ) , 12 ) =0 then 'Y' else 'N' end = 'Y'
and case when pmagt = 0 then D.branch_code else E.branch_code end = :Branch
and pmagt = :Agency
END GET_RSM_LIFE_AGENT_DUES;
Error.....
Error(2,67): PLS-00049: bad bind variable 'YEAR'
Error(2,67): PLS-00103: Encountered the symbol "" when expecting one of the following: <an identifier> <a double-quoted delimited-identifier> current delete exists prior
Error(2,84): PLS-00049: bad bind variable 'MONTH'
Remove colons from within the procedure. Those are procedure's parameters, so use them as such. Pass their values as e.g.
declare
l_out sys_refcursor;
begin
GET_RSM_LIFE_AGENT_DUES (l_out, :Year, :Month, :Branch, :Agency);
end;

How to set a specific condition to a new Parameter in T-SQL

I have an existing code, to which I have to add new Parameter -
#Depreciation 'Yes' or 'No'
if #Depreciation = 1 (which I believe corresponds to 'Yes')
then I want the certain condition of an existing code will be
FALSE (I marked that code section with the '-- ***' ),
and the vise versa -
if #Depreciation = 0 ('No')
then I want that condition in the code will be
TRUE
The conditions is
(NOT (acct.[GLAccountCode] IN (N'9040',N'9047',N'4130')))
located after the 1st WHERE in the code below.
Please, don't pay too much attention to the entire code.
The only parts that I have to modify are -
'DECLARE #Depreciation....'
and after the first 'WHERE ..... ' - I marked with -- ***
DECLARE #FYMonthBOP date = '07-01-2016'
DECLARE #FYMonthEOP date = '07-01-2018'
DECLARE #GLProgramGroupsWHID int = -1
DECLARE #GLProgramsWHID_Groups int = -1
DECLARE #GLProgramGroupSetsWHID int = -1
DECLARE #Depreciation bit = 1 -- *** This is my added Parameter
SELECT
gl0.GLGroupLevel0Name
, gl0.Ordinal AS Ordinal0
, [Dimension].GLGroupLevel1.GLGroupLevel1Name
, [Dimension].GLGroupLevel1.Ordinal AS Ordinal1
, gl2.GLGroupLevel2Name
, gl2.Ordinal AS Ordinal2
, acct.GLAccountCode
, acct.GLAccountName
, setname.WHID AS WHIDGroupSetName
, setname.GroupSetName
, pgm.GLProgramCode + N' ' + pgm.GLProgramName AS Program
, grp.GroupName
, grp.WHID AS WHIDGroupName
, grp.Ordinal AS OrdinalGroupName
, d.FYQuarterLabel AS FQ
, trans.Amount AS Amount
, pgm.[WHID] AS WHIDProgram
, pgm.Ordinal AS OrdinalProgram
, d.FYMonthNumber
, d.FYMonthShortLabel
, d.FYQuarterNumber
, d.FYNumber
, d.FYLabel
, d.YearMonthSort
, IIF(EOMonth(mm.DateThru) < #FYMonthEOP, EOMonth(mm.DateThru),
#FYMonthEOP) AS [DateThru]
FROM
([Dimension].GLGroupLevel2 gl2
INNER JOIN [Dimension].GLAccount acct ON gl2.[WHID] =
acct.GLGroupLevel2FK
INNER JOIN [Dimension].GLGroupLevel0 gl0
INNER JOIN [Dimension].GLGroupLevel1 ON gl0.[WHID] =
[Dimension].GLGroupLevel1.GLGroupLevel0FK ON
gl2.GLGroupLevel1FK =
[Dimension].GLGroupLevel1.[WHID]
INNER JOIN Fact.GLTransactionsMonthly trans ON acct.[WHID] =
trans.GLAccountFK
INNER JOIN [Dimension].GLProgram pgm ON trans.[GLProgramFK] =
pgm.[WHID] AND trans.[GLProgramFK] =
pgm.[WHID] AND trans.[GLProgramFK] = pgm.[WHID]
INNER JOIN [Dimension].[Date] d ON trans.EffectiveMonth = d.[Date]
AND trans.EffectiveMonth = d.[Date]
AND trans.EffectiveMonth = d.[Date]
INNER JOIN [Dimension].GLRegion ON pgm.GLRegionFK =
[Dimension].GLRegion.[WHID] AND pgm.GLRegionFK =
[Dimension].GLRegion.[WHID]
INNER JOIN [Reports].GLProgramGroupMapping map ON map.GLProgramFK =
pgm.[WHID]
INNER JOIN [Reports].GLProgramGroup grp ON grp.WHID =
map.GLProgramGroupFK
INNER JOIN [Reports].GLProgramGroupSet setname ON setname.WHID =
grp.GLProgramGroupSetFK)
CROSS APPLY (SELECT MAX(t.EffectiveMonth) AS [DateThru] FROM
Fact.GLTransactionsMonthly t WITH (NoLock)) mm
-- *** This, below -
WHERE (
(NOT (acct.[GLAccountCode] IN (N'9040',N'9047',N'4130')))
-- *** is the condition I want to execute, if my Parameter = False, and not
-- *** to execute, if my Parameter = True
AND (trans.[EffectiveMonth] BETWEEN #FYMonthBOP AND #FYMonthEOP)
AND ((setname.WHID IN (#GLProgramGroupSetsWHID)) OR (-1 IN
(#GLProgramGroupSetsWHID)))
AND ((grp.WHID IN (#GLProgramGroupsWHID)) OR (-1 IN
(#GLProgramGroupsWHID)))
AND ((pgm.[WHID] IN (#GLProgramsWHID_Groups)) OR
(-1 IN (#GLProgramsWHID_Groups)))
AND (
(pgm.[WHID] IN (
SELECT DISTINCT
f.[GLProgramFK]
FROM
Fact.GLTransactionsMonthly f
INNER JOIN [Dimension].[GLAccount] acct ON
f.[GLAccountFK] = acct.[WHID]
WHERE
(f.[EffectiveMonth] BETWEEN #FYMonthBOP AND #FYMonthEOP)
AND (NOT (acct.[GLAccountCode] IN (N'9040',N'9047')))
AND (acct.[GLAccountCode] BETWEEN '5000' AND '9999')
GROUP BY
f.[GLProgramFK]
HAVING
(SUM(f.[Amount]) <> 0))
)
OR
(pgm.[WHID] IN (
SELECT DISTINCT
f.[GLProgramFK]
FROM
Fact.GLTransactionsMonthly f
INNER JOIN [Dimension].[GLAccount] acct ON
f.[GLAccountFK] = acct.[WHID]
WHERE
(f.[EffectiveMonth] BETWEEN #FYMonthBOP AND #FYMonthEOP)
AND (NOT (acct.[GLAccountCode] IN (N'4130')))
AND (acct.[GLAccountCode] BETWEEN '4000' AND '4999')
GROUP BY
f.[GLProgramFK]
HAVING
(SUM(f.[Amount]) <> 0))
)
OR
(pgm.[GLProgramCode] IN ('549'))
)
)
Like this:
(
(
#Depreciation = 0 /* FALSE AND EXISTING CONDITION */
and NOT (acct.[GLAccountCode] IN (N'9040',N'9047',N'4130'))
)
or
(
#Depreciation = 1 /* OR TRUE AND NOT EXISTING CONDITION */
and (acct.[GLAccountCode] IN (N'9040',N'9047',N'4130'))
)
)

How to get a windowed function working in WHERE clause

I know that there are quite many threads on "Windowed functions can only appear in the select or ORDER BY clases" topic, but I have read them through and just don't seem to get any of those trick to work for me. So here I go.
My Query you can see below the line. I have highlighted the part of the Query which is "causing" me issues or problems. The thing is that I would like to get
"LocalCurrentAmount not between -1.000000 and 1.000000"
in somehow. I have tried the CTE versioon, but somehow didn't work and my declare tables and then the details view started causing problems.
Would really appreciate your help!
Jaanis
declare #exceptions1 table (CustomerCode varchar(7), Exception_comment varchar(15));
insert into #exceptions1 (CustomerCode, Exception_comment)
VALUES
(3514437,'Exception'),(3500977,'Exception'),(3295142,'Exception'), ...
declare #exceptions2 table (CustomerCode2 varchar(7), Exception_comment2 varchar(15));
insert into #exceptions2 (CustomerCode2, Exception_comment2)
VALUES
(3390437,'VIP SE') ,(3390438,'VIP SE') ,(3390481,'VIP SE'), ...
declare #exceptions3 table (CustomerCode3 varchar(7), Exception_comment3 varchar(15));
insert into #exceptions1 (CustomerCode, Exception_comment)
VALUES
(1530350, 'DK Exception'), (1533834, 'DK Exception'), (1530002, 'DK Exception'), ...
with Details as
(
select ard.AccountsReceivableHeaderID, sum(ard.TransactionAmountOC) as DetailAmountOC , Max(DetailSequenceCode) as DetailSequenceCode, Max( ard.BatchDate) as BatchDate
from dmbase.fAccountsReceivableDetail ard
join dmbase.fAccountsReceivable arh on ard.AccountsReceivableHeaderID = arh.AccountsReceivableID
where ard.BatchDate <= getdate()
group by AccountsReceivableHeaderID
)
SELECT
comp.CompanyCode
,convert(varchar(10),ar.InvoiceDate, 103) as Invoice_date -- dd/MM/yyyy format
,case
when ar.IsCreditMemo = 'Y' then 'Memo (Credit/Debit)'
when ar.InvoiceCode = '0' then 'Payment'
else 'Invoice'
end as Description
,isnull(cm.SummaryInvoiceCode, ar.InvoiceSummaryCode) InvoiceSummaryCode
,case
when len(ar.InvoiceSequenceCode) = '1' then CONCAT(ar.InvoiceCode,'-000',ar.InvoiceSequenceCode)
when len(ar.InvoiceSequenceCode) = '2' then CONCAT(ar.InvoiceCode,'-00',ar.InvoiceSequenceCode)
when len(ar.InvoiceSequenceCode) = '3' then CONCAT(ar.InvoiceCode,'-0',ar.InvoiceSequenceCode)
else CONCAT(ar.InvoiceCode,'-',ar.InvoiceSequenceCode)
end as Invoice#
,**(ar.OriginalInvoiceAmountOC
+
case
when row_number() over (partition by AccountsReceivableID order by ar.InvoiceCode) = 1 then isnull(vat.vatAdjustment, 0)
else 0
end
+
coalesce(det.DetailAmountOC, 0)) * coalesce(cer.CurrencyExchangeRate, ar.CurrencyExchangeRate) AS LocalCurrentAmount**
,(ar.OriginalInvoiceAmountOC
+
case
when row_number() over (partition by AccountsReceivableID order by ar.InvoiceCode) = 1 then isnull(vat.vatAdjustment, 0)
else 0
end
+ coalesce(det.DetailAmountOC, 0)) AS CurrentAmount
,ar.OriginalInvoiceAmountOC
+
case
when row_number() over (partition by AccountsReceivableID order by ar.InvoiceCode) = 1 then isnull(vat.vatAdjustment, 0)
else 0
end as OriginalInvoiceAmountOC
,ar.InvoiceCurrencyCode
,cust.CustomerCode
,upper(cust.CustomerName) as CustomerName
from
dmbase.fAccountsReceivable ar
INNER JOIN dmbase.dlocation loc
ON loc.LocationID = ar.LocationID
INNER JOIN dmbase.dCustomer cust
ON cust.CustomerID = ar.CustomerID
LEFT JOIN dmbase.VatAdjustment vat
on ar.InvoiceCode = vat.contractNumber
and ar.InvoiceSequenceCode = vat.invoiceSequence
and cust.CustomerCode = vat.CustomerNumber
and loc.CompanyCode = vat.companyCode
inner join dmbase.dCompany comp
on (ar.CompanyID = comp.CompanyID)
left join dmbase.dAccountsReceivableInvoiceStatus aris
on (aris.ARInvoiceStatusAMID=ar.ARInvoiceStatusAMID)
left hash join Details det
on (ar.AccountsReceivableID = det.AccountsReceivableHeaderID)
left join dmbase.dCurrencyExchangeRate cer
on (comp.CompanyCode = cer.CompanyCode
and ar.InvoiceCurrencyCode = cer.CurrencyCode
and case ar.InvoiceDate when '1900-01-01' then getdate() else ar.InvoiceDate end between cer.ValidFrom and cer.ValidTo)
left join dmbase.fContractClosedHeader ccd
on ccd.ContractNumber = ar.InvoiceCode
and ccd.ContractSeqNumber = ar.InvoiceSequenceCode
and ccd.CompanyID = ar.CompanyID
and ccd.ContractNumber!='0'
and ccd.CreditMemoContractNumber != '0'
left join dmbase.fAccountsReceivableHeader cm
on ccd.CreditMemoContractNumber = cm.ContractNumber
and ccd.CreditMemoSequenceCode = cm.ContractSeqNumber
and cm.CompanyID = ccd.CompanyID
where
(aris.ARInvoiceStatusCode = 'OP' or (ar.LastPaymentDate >= getdate())
or (ar.TotalAdjustmentsAmountOC <> 0 and ar.CurrentAmountLC = 0
and (ar.OriginalInvoiceAmountOC + isnull(vat.vatAdjustment, 0) ) + coalesce(det.DetailAmountOC, 0) <> 0)
)
and ar.OriginalInvoiceAmountOC <= 0
and ar.IsCreditMemo = 'Y' -- ainult Memo (Credit/Debit)
and cust.InternalCustomerType = 'External'
and cust.CustomerName not in ('RR AJM', 'RAMIRENT', 'Ramirent')
and cust.CustomerName not like '%[7][0-9][0-9][0-9]%'
and ar.InvoiceDate <= EOMONTH(getdate(),-3
and cust.CustomerCode NOT IN
(select CustomerCode from #exceptions1
union
select CustomerCode2 from #exceptions2
union
select CustomerCode3 from #exceptions3)
order by Invoice_date
When using a Window function, like you said in your post, you can't use it in the WHERE clause. The common solution, therefore, is to use a CTE and reference it in the WHERE outside of it. I've used your CTE, however, without any kind of sample data this is a total guess. I've also left a lot of comments for you, and changed some other parts of the SQL, as some of the clauses you have will effect your query's performance.
WITH
Details AS
(SELECT ard.AccountsReceivableHeaderID,
SUM(ard.TransactionAmountOC) AS DetailAmountOC,
MAX(DetailSequenceCode) AS DetailSequenceCode,
MAX(ard.BatchDate) AS BatchDate
FROM dmbase.fAccountsReceivableDetail ard
JOIN dmbase.fAccountsReceivable arh ON ard.AccountsReceivableHeaderID = arh.AccountsReceivableID
WHERE ard.BatchDate <= GETDATE()
GROUP BY AccountsReceivableHeaderID),
Summary AS(
SELECT comp.CompanyCode,
CONVERT(varchar(10), ar.InvoiceDate, 103) AS Invoice_date, -- dd/MM/yyyy format
CASE
WHEN ar.IsCreditMemo = 'Y' THEN 'Memo (Credit/Debit)'
WHEN ar.InvoiceCode = '0' THEN 'Payment'
ELSE 'Invoice'
END AS Description,
ISNULL(cm.SummaryInvoiceCode, ar.InvoiceSummaryCode) AS InvoiceSummaryCode,
CASE
WHEN LEN(ar.InvoiceSequenceCode) = '1' THEN CONCAT(ar.InvoiceCode, '-000', ar.InvoiceSequenceCode)
WHEN LEN(ar.InvoiceSequenceCode) = '2' THEN CONCAT(ar.InvoiceCode, '-00', ar.InvoiceSequenceCode)
WHEN LEN(ar.InvoiceSequenceCode) = '3' THEN CONCAT(ar.InvoiceCode, '-0', ar.InvoiceSequenceCode)
ELSE CONCAT(ar.InvoiceCode, '-', ar.InvoiceSequenceCode)
END AS Invoice#,
(ar.OriginalInvoiceAmountOC + CASE
WHEN ROW_NUMBER() OVER (PARTITION BY AccountsReceivableID ORDER BY ar.InvoiceCode) = 1 THEN ISNULL(vat.vatAdjustment, 0)
ELSE 0
END + COALESCE(det.DetailAmountOC, 0)) * COALESCE(cer.CurrencyExchangeRate, ar.CurrencyExchangeRate) AS LocalCurrentAmount,
(ar.OriginalInvoiceAmountOC + CASE
WHEN ROW_NUMBER() OVER (PARTITION BY AccountsReceivableID ORDER BY ar.InvoiceCode) = 1 THEN ISNULL(vat.vatAdjustment, 0)
ELSE 0
END + COALESCE(det.DetailAmountOC, 0)) AS CurrentAmount,
ar.OriginalInvoiceAmountOC + CASE
WHEN ROW_NUMBER() OVER (PARTITION BY AccountsReceivableID ORDER BY ar.InvoiceCode) = 1 THEN ISNULL(vat.vatAdjustment, 0)
ELSE 0
END AS OriginalInvoiceAmountOC,
ar.InvoiceCurrencyCode,
cust.CustomerCode,
UPPER(cust.CustomerName) AS CustomerName
FROM dmbase.fAccountsReceivable ar
INNER JOIN dmbase.dlocation loc ON loc.LocationID = ar.LocationID
INNER JOIN dmbase.dCustomer cust ON cust.CustomerID = ar.CustomerID
LEFT JOIN dmbase.VatAdjustment vat ON ar.InvoiceCode = vat.contractNumber
AND ar.InvoiceSequenceCode = vat.invoiceSequence
AND cust.CustomerCode = vat.CustomerNumber
AND loc.CompanyCode = vat.companyCode
INNER JOIN dmbase.dCompany comp ON (ar.CompanyID = comp.CompanyID)
LEFT JOIN dmbase.dAccountsReceivableInvoiceStatus aris ON (aris.ARInvoiceStatusAMID = ar.ARInvoiceStatusAMID)
LEFT HASH JOIN Details det ON (ar.AccountsReceivableID = det.AccountsReceivableHeaderID)
LEFT JOIN dmbase.dCurrencyExchangeRate cer ON (comp.CompanyCode = cer.CompanyCode
AND ar.InvoiceCurrencyCode = cer.CurrencyCode
AND CASE ar.InvoiceDate WHEN '1900-01-01' THEN GETDATE()ELSE ar.InvoiceDate END BETWEEN cer.ValidFrom AND cer.ValidTo)
LEFT JOIN dmbase.fContractClosedHeader ccd ON ccd.ContractNumber = ar.InvoiceCode
AND ccd.ContractSeqNumber = ar.InvoiceSequenceCode
AND ccd.CompanyID = ar.CompanyID
AND ccd.ContractNumber != '0'
AND ccd.CreditMemoContractNumber != '0'
LEFT JOIN dmbase.fAccountsReceivableHeader cm ON ccd.CreditMemoContractNumber = cm.ContractNumber
AND ccd.CreditMemoSequenceCode = cm.ContractSeqNumber
AND cm.CompanyID = ccd.CompanyID
WHERE (aris.ARInvoiceStatusCode = 'OP'
OR (ar.LastPaymentDate >= GETDATE())
OR (ar.TotalAdjustmentsAmountOC <> 0
AND ar.CurrentAmountLC = 0
AND (ar.OriginalInvoiceAmountOC + ISNULL(vat.vatAdjustment, 0)) + COALESCE(det.DetailAmountOC, 0) <> 0)) --Why ISNULL for one, COALESCE for the other? Both will make the query non-SARGable
AND ar.OriginalInvoiceAmountOC <= 0
AND ar.IsCreditMemo = 'Y' -- ainult Memo (Credit/Debit)
AND cust.InternalCustomerType = 'External'
AND cust.CustomerName NOT IN ('RR AJM', 'RAMIRENT', 'Ramirent')
AND cust.CustomerName NOT LIKE '%[7][0-9][0-9][0-9]%' --A leading wildcard is going to perform slow
AND ar.InvoiceDate <= EOMONTH(DATEADD(DAY, -3, GETDATE())) --I have changed this from EOMONTH(GETDATE(), -3 (which made no sense)
AND NOT EXISTS (SELECT 1
FROM #exceptions1 E
WHERE E.CustomerCode = cust.CustomerCode) --Changed to EXISTS binned UNION you should use UNION ALL if you're doing something like this, it'll be quicker)
AND NOT EXISTS (SELECT 1
FROM #exceptions2 E
WHERE E.CustomerCode = cust.CustomerCode) --Changed to EXISTS binned UNION (you should use UNION ALL if you're doing something like this, it'll be quicker)
AND NOT EXISTS (SELECT 1
FROM #exceptions3 E
WHERE E.CustomerCode = cust.CustomerCode)) --Changed to EXISTS binned UNION you should use UNION ALL if you're doing something like this, it'll be quicker)
SELECT *
FROM Summary
WHERE LocalCurrentAmount NOT BETWEEN -1 AND 1
ORDER BY Invoice_date;
It's worth noting that the above sql is completely untested. I do not have access to your server, or data, so I'm purely relying on "my eye" to note any errors.

Getting Ambiguous Column Name Error

So I'm pretty new to this program and cannot figure out why I am getting this error.
Here is the qry.
SELECT policy_no,
phase_code,
sub_phase_code,
Duplicate_Indicator = CASE
WHEN Sum(1) <> 1 THEN 'DUPLICATE'
ELSE 'NOT DUPLICATE'
END
FROM qrypolicylistfornydefpremasset_re
RIGHT JOIN (SELECT TOP 100 PERCENT tblinsurance.policy_no,
tblinsurance.phase_code,
tblinsurance.sub_phase_code,
tblinsurance.prodtype,
tblinsurance.paid_to_date,
tblinsurance.val_date,
tblinsurance.issue_date,
tblinsurance.schednp,
Sum(tblinsurance.gross_annlzd_prem) AS
SumOfGROSS_ANNLZD_PREM,
Sum(tblinsurance.statnetpremium) AS
SumOfStatNetPremium,
Sum(tblinsurance.netdefpremium) AS
SumOfNetDefPremium,
Sum(tblinsurance.netdefextra) AS
SumOfNetDefExtra,
Sum(tblinsurance.netdefpremiumadj) AS
SumOfNetDefPremiumAdj,
Sum(tblinsurance.netdefextraadj) AS
SumOfNetDefExtraAdj,
NetvsGrossInd = CASE
WHEN
[netdefpremium] = [netdefpremiumadj]
THEN
'Net'
ELSE 'Gross'
END,
Sum(tblinsurance.amount_inforce) AS
SumOfAMOUNT_INFORCE,
Sum(tblinsurance.pua_face) AS
SumOfPUA_FACE,
Sum(tblinsurance.oyt_face) AS
SumOfOYT_FACE
FROM tblinsurance
WHERE ( ( ( tblinsurance.company_code ) = 'NL' )
AND ( ( tblinsurance.term_reason ) = 'A' )
AND ( ( tblinsurance. issue_date ) <= [val_date] ) )
GROUP BY tblinsurance.policy_no,
tblinsurance.phase_code,
tblinsurance.sub_phase_code,
tblinsurance.prodtype,
tblinsurance.paid_to_date,
tblinsurance.val_date,
tblinsurance.issue_date,
tblinsurance.schednp,
CASE
WHEN [netdefpremium] = [netdefpremiumadj] THEN
'Net'
ELSE 'Gross'
END
HAVING (( ( Sum(tblinsurance.netdefpremium) ) <> 0 )))Work
ON policy_no = qrypolicylistfornydefpremasset_re.policy_no
AND phase_code = qrypolicylistfornydefpremasset_re.phase_code
AND sub_phase_code =
qrypolicylistfornydefpremasset_re.sub_phase_code
GROUP BY policy_no,
phase_code,
sub_phase_code
Where I am getting the ambiguous colum name is on the Fields POLICY_NO, PHASE_CODE, SUB_PHASE_CODE, but only in the On and GROUP by at the end and the ones in the SELECT in the beginning.
well, you've got these fields in both
qryPolicyListforNYDefPRemAsset_Re
and in your subquery Work
so prefix them with the right table (or better, use aliases).
I prefixed with Work in SELECT and GROUP BY and JOIN I may be wrong for SELECT and GROUP BY (maybe you need q, alias for qryPolicyListforNYDefPRemAsset_Re) :I'm like Sql, your query is too ambiguous for me ;)
SELECT
Work.POLICY_NO,
Work.PHASE_CODE,
Work.SUB_PHASE_CODE,
Duplicate_Indicator = case when
SUM(1) <> 1 then 'DUPLICATE'
else 'NOT DUPLICATE'
end
FROM
qryPolicyListforNYDefPRemAsset_Re q
RIGHT JOIN
(SELECT top 100 percent
t.POLICY_NO,
t.PHASE_CODE,
t.SUB_PHASE_CODE,
t.ProdType,
t.PAID_TO_DATE,
t.VAL_DATE,
t.ISSUE_DATE,
t.SchedNP,
Sum(t.GROSS_ANNLZD_PREM) AS SumOfGROSS_ANNLZD_PREM,
Sum(t.StatNetPremium) AS SumOfStatNetPremium,
Sum(t.NetDefPremium) AS SumOfNetDefPremium,
Sum(t.NetDefExtra) AS SumOfNetDefExtra,
Sum(t.NetDefPremiumAdj) AS SumOfNetDefPremiumAdj,
Sum(t.NetDefExtraAdj) AS SumOfNetDefExtraAdj,
NetvsGrossInd = Case when [NetDefPremium]=[NetDefPremiumAdj] then 'Net' Else 'Gross' END,
Sum(t.AMOUNT_INFORCE) AS SumOfAMOUNT_INFORCE,
Sum(t.PUA_FACE) AS SumOfPUA_FACE,
Sum(t.OYT_FACE) AS SumOfOYT_FACE
FROM tblInsurance t
WHERE (((t.COMPANY_CODE)='NL') AND ((t.TERM_REASON)='A') AND ((t.ISSUE_DATE)<=[VAL_DATE]))
GROUP BY
t.POLICY_NO,
t.PHASE_CODE,
t.SUB_PHASE_CODE,
t.ProdType,
t.PAID_TO_DATE,
t.VAL_DATE,
t.ISSUE_DATE,
t.SchedNP,
Case when [NetDefPremium]=[NetDefPremiumAdj] then 'Net' Else 'Gross' END
HAVING (((Sum(t.NetDefPremium))<>0))
)Work
ON
Work.POLICY_NO = q.POLICY_NO AND
Work.qPHASE_CODE= q.PHASE_CODE AND
Work.SUB_PHASE_CODE = q.SUB_PHASE_CODE
GROUP BY
Work.POLICY_NO,
Work.PHASE_CODE,
Work.SUB_PHASE_CODE

Resources