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
Related
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
I have three fields I want to filter my query by. I want to query even if 1 or 2 of the fields are empty (passing an empty string). I can figure out 1 field, but once I add the other two, I do not get any results. Curly brackets are my form fields that get passed to the query.
IF '{Envelope Size}' <> ''
SELECT Tools.ToolNo,
Tools.[Name]
FROM Tools
LEFT JOIN
(
SELECT AdditionalInfo.OwnerID,
AdditionalInfo.UserDefined3,
AdditionalInfo.UserDefined4,
AdditionalInfo.UserDefined5,
AdditionalInfo.UserDefined10,
AdditionalInfo.UserDefined24
FROM AdditionalInfo
WHERE AdditionalInfo.ModuleID = 35
) AS EnvStyle ON Tools.ToolID = EnvStyle.OwnerID
WHERE EnvStyle.UserDefined24 LIKE '{Envelope Size}';
ELSE
SELECT Tools.ToolNo,
Tools.[Name]
FROM Tools
LEFT JOIN
(
SELECT AdditionalInfo.OwnerID,
AdditionalInfo.UserDefined3,
AdditionalInfo.UserDefined4,
AdditionalInfo.UserDefined5,
AdditionalInfo.UserDefined12
FROM AdditionalInfo
WHERE AdditionalInfo.ModuleID = 35
) AS EnvStyle ON Tools.ToolID = EnvStyle.OwnerID
WHERE EnvStyle.UserDefined3 <> 'Stationery'
AND EnvStyle.UserDefined4 = (CASE WHEN '{Env. Height}' = '' THEN 'NULL' ELSE '{Env. Height}' END)
AND EnvStyle.UserDefined5 = (CASE WHEN '{Env. Width}' = '' THEN 'NULL' ELSE '{Env. Width}' END)
AND EnvStyle.UserDefined12 = (CASE WHEN '{Flap Size}' = '' THEN 'NULL' ELSE '{Flap Size}' END);
I'm not exactly clear on what your data structure is and the curly braces are throwing me off a bit, but maybe something like this might work for you. You could change your filter conditions to use an OR with a CASE to force a match in those cases when the values are blank. Again, I'm not sure of your structure and the below is just following your example, but hopefully this might get you in the right direction.
IF '{Envelope Size}' <> ''
SELECT Tools.ToolNo,
Tools.[Name]
FROM Tools
LEFT JOIN
(
SELECT AdditionalInfo.OwnerID,
AdditionalInfo.UserDefined3,
AdditionalInfo.UserDefined4,
AdditionalInfo.UserDefined5,
AdditionalInfo.UserDefined10,
AdditionalInfo.UserDefined24
FROM AdditionalInfo
WHERE AdditionalInfo.ModuleID = 35
) AS EnvStyle ON Tools.ToolID = EnvStyle.OwnerID
WHERE EnvStyle.UserDefined24 LIKE '{Envelope Size}';
ELSE
SELECT Tools.ToolNo,
Tools.[Name]
FROM Tools
LEFT JOIN
(
SELECT AdditionalInfo.OwnerID,
AdditionalInfo.UserDefined3,
AdditionalInfo.UserDefined4,
AdditionalInfo.UserDefined5,
AdditionalInfo.UserDefined12
FROM AdditionalInfo
WHERE AdditionalInfo.ModuleID = 35
) AS EnvStyle ON Tools.ToolID = EnvStyle.OwnerID
WHERE EnvStyle.UserDefined3 <> 'Stationery'
AND (EnvStyle.UserDefined4 = {Env.Height}
OR 1 = CASE WHEN {Env.Height} = '' THEN 1 ELSE 0 END)
AND (EnvStyle.UserDefined5 = {Env.Width}
OR 1 = CASE WHEN {Env.Width} = '' THEN 1 ELSE 0 END)
AND (EnvStyle.UserDefined12 = {Flap Size}
OR 1 = CASE WHEN {Flap Size} = '' THEN 1 ELSE 0 END);
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.
SELECT DT.TenantDescription
,DT.PropertyNumber
,DT.UnitNo
,DT.AdressLn1
,DT.AddressLn2
,DT.AddressSituation
,(
CASE
WHEN DT.TransactionCode = 1
THEN DT.New_TransactionValue
ELSE 0
END
) AS RentDue
,(
CASE
WHEN DT.TransactionCode = 2
THEN DT.New_TransactionValue
ELSE 0
END
) AS OTHERSUMSDUE
,(
CASE
WHEN DT.TransactionCode = 3
THEN DT.New_TransactionValue
ELSE 0
END
) AS ARREARSBFWD
,(
CASE
WHEN DT.TransactionCode = 4
THEN DT.New_TransactionValue
ELSE 0
END
) AS ARREARSCFWD
,(
CASE
WHEN DT.TransactionCode = 5
THEN DT.New_TransactionValue
ELSE 0
END
) AS IRRECOVERABLERENT
,(
CASE
WHEN DT.TransactionCode > 5
THEN DT.New_TransactionValue
ELSE 0
END
) AS Expenditure
FROM (
SELECT * * (
SELECT New_TenantNameOnly
FROM New_Rentmaster Rm
WHERE Rm.New_rentmasterId = PD.new_rentmasterid
) AS TenantDescription
,* * (
SELECT [New_UnitNumber]
FROM new_propertyunits NPU
WHERE NPU.[New_propertyunitsId] = PD.[new_unitnumberid]
) AS UnitNo
,(
SELECT New_AddressLine1
FROM New_address
WHERE New_addressId = (
SELECT New_addressid
FROM New_PropertyMaster PM
WHERE PM.new_propertymasterid = PD.[new_propertynumbernameid]
)
) AS AdressLn1
,(
SELECT New_AddressLine2
FROM New_address
WHERE New_addressId = (
SELECT New_addressid
FROM New_PropertyMaster PM
WHERE PM.new_propertymasterid = PD.[new_propertynumbernameid]
)
) AS AddressLn2
,(
SELECT TT.[New_TransactionTypeCode] AS TransactionCode
FROM New_transactiontype TT
WHERE [New_transactiontypeId] = PD.[new_transactioncodenameid]
) AS TransactionCode
,(
SELECT New_PropertyNumber
FROM New_PropertyMaster PM
WHERE PM.new_propertymasterid = PD.[new_propertynumbernameid]
) AS PropertyNumber
,(
SELECT New_UnitAddressIdName
FROM New_propertyunits NPU
WHERE NPU.[New_propertyunitsId] = PD.[new_unitnumberid]
) AS AddressSituation
,PD.New_TransactionValue
FROM New_PropertyDetails PD
) AS DT
The above piece of code works fine
Now I want to make changes to the above column (the name is aliased to TenantDescription)
where I want to replace the above column with the following code
Select New_TenantNameOnly from New_Rentmaster Rm
New_TenantNumber IN
(Select MAX(New_TenantNumber) from new_rentmaster GROUP BY [New_Unit_No],[New_Propety_Number])
then it gives me an error
Subquery returns more than one value
This code is supposed to return more than one value
So what should I do about it >??
If you're wanting to bring back multiple results, you ought to be thinking about using joins rather than subqueries. An Inner Join looks something like this:
SELECT *
FROM HumanResources.Employee AS e
INNER JOIN Person.Person AS p
ON e.BusinessEntityID = p.BusinessEntityID
this will produce as many rows as can be produced by matching rows from each table based on the ON condition (e.g. if there are two rows in Employee with BusinessEntityID of 1, and three rows in Person with BusinessEntityID of 1, the above will produce six rows in the result set where BusinessEntityID is 1)
I'm trying to convert a report query from Access to SQL SERVER 2008. Using the same database but i can't get the same results. not even close. The Access query is like this:
SELECT Sum(INPUT_ItemSaleLines.TaxExclusiveTotal) AS TotalexTax,([TotalexTax])- Sum( Nz([SumOfTaxExclusiveAmount])+ Nz([CostOfGoodsSoldAmount])+ Nz
(
Nz
( IIf
( Left([Input_Items.ItemNumber],5)='31-63',136*[Quantity]/1000,
IIf(Left([Input_Items.ItemNumber],6)='34S-63',200*[Quantity]/1000)
)
)+ Nz
( IIf
( Left([Input_Items.ItemNumber],5)='34-63',250*[Quantity]/1000,
IIf(Left([Input_Items.ItemNumber],6)='26-63',250*[Quantity]/1000)
)
)
)
) AS Margin,
INPUT_Cards_1.Name AS SalesPerson, INPUT_Sales.SalesPersonID,
INPUT_Sales.InvoiceStatusID, INPUT_Cards.Name, INPUT_Items.ItemName,
Sum(INPUT_ItemSaleLines.Quantity) AS TotalQty,
Sum(INPUT_ItemSaleLines.CostOfGoodsSoldAmount) AS TotalCOGS,
Count(INPUT_Sales.SaleID) AS [Number of Sales],
Sum(qryShippingTotalexGST.SumOfTaxExclusiveAmount) AS ShippingTotal
FROM
( qryShippingTotalexGST RIGHT JOIN
(
(
(
INPUT_Items INNER JOIN INPUT_ItemSaleLines
ON INPUT_Items.ItemID = INPUT_ItemSaleLines.ItemID
) INNER JOIN INPUT_Sales ON INPUT_ItemSaleLines.SaleID = INPUT_Sales.SaleID
) INNER JOIN INPUT_Cards ON INPUT_Sales.CardRecordID = INPUT_Cards.CardRecordID
) ON qryShippingTotalexGST.JobID = INPUT_ItemSaleLines.JobID
) LEFT JOIN INPUT_Cards AS INPUT_Cards_1 ON INPUT_Sales.SalesPersonID = INPUT_Cards_1.CardRecordID
WHERE
(((INPUT_Sales.Date) Between [Forms]![MenuReports]![StartDate] And [Forms]![MenuReports]![EndDate]))
GROUP BY INPUT_Items.ItemNumber,
INPUT_Cards_1.Name, INPUT_Sales.SalesPersonID, INPUT_Sales.InvoiceStatusID,
INPUT_Cards.Name, INPUT_Items.ItemName
HAVING
(((INPUT_Sales.InvoiceStatusID)<>"OR"));
Then the SQL Server script that i write like this:
SELECT MYOBItems.ItemName, MYOBCards.Name AS SalesPerson, MYOBCards1.Name,
SUM(MYOBsalesLines.Qty) AS TotalQty,
SUM(MYOBsalesLines.CostOfGoodsSoldAmount) AS TotalCOGS,
COUNT(MYOBSales.SaleID) AS NumberOfSales,
SUM(MYOBsalesLines.TaxExclusiveAmount) AS TotalexTax,
SUM(cast(MYOBJobsShippingTotals.TaxExclusiveAmount AS Decimal(18,2))) AS ShippingTotal,
(SUM(MYOBsalesLines.TaxExclusiveAmount)) - SUM
(
COALESCE(cast(MYOBJobsShippingTotals.TaxExclusiveAmount AS Decimal(18,2)),0)+ COALESCE(MYOBsalesLines.CostOfGoodsSoldAmount,0)+ COALESCE
(
COALESCE
(
CASE
WHEN LEFT(MYOBItems.ItemNumber,5) = '31-63' THEN (136*MYOBsalesLines.Qty/1000)
WHEN LEFT(MYOBItems.ItemNumber,6) = '34S-63' THEN (200*MYOBsalesLines.Qty/1000)
ELSE 0
END, 0
)+ COALESCE
(
CASE
WHEN LEFT(MYOBItems.ItemNumber,5) = '34-63' THEN (250*MYOBsalesLines.Qty/1000)
WHEN LEFT(MYOBItems.ItemNumber,6) = '26-63' THEN (250*MYOBsalesLines.Qty/1000)
ELSE 0
END , 0
), 0
)
)AS Margin
, MYOBSales.InvoiceStatusID FROM
( MYOBJobsShippingTotals RIGHT JOIN
(
(
(
MYOBItems INNER JOIN MYOBsalesLines
ON MYOBItems.ItemID = MYOBsalesLines.ItemID
) INNER JOIN MYOBSales ON MYOBsalesLines.SaleID = MYOBSales.SaleID
AND MYOBSales.ElevateCompanyID = MYOBsalesLines.ElevateCompanyID
) INNER JOIN MYOBCards AS MYOBCards1 ON MYOBSales.CardRecordID = MYOBCards1.CardRecordID
AND MYOBsalesLines.ElevateCompanyID = MYOBCards1.ElevateCompanyID
AND MYOBSales.ElevateCompanyID = MYOBCards1.ElevateCompanyID
) ON MYOBJobsShippingTotals.JobID = MYOBsalesLines.JobID
) LEFT JOIN MYOBCards ON MYOBSales.SalesPersonID = MYOBCards.CardRecordID
GROUP BY MYOBItems.ItemName, MYOBCards.Name,
MYOBCards1.Name, MYOBSales.InvoiceStatusID
I suspect there was something wrong with the joined tables but not sure how to fix it.
Is there any mistake in my SQL Server script that is not relevant with the Access syntax?
Thank for the help in advance. and sorry for my long scripts.
Your SQL server query is missing the WHERE and HAVING clauses of the MS Access query, it's GROUP BY clause doesn't have the same number or order of columns as the MS Access query, and has additional JOIN criteria that wasn't in the MS Access query.
A more faithful conversion would look like this:
SELECT SUM(MYOBsalesLines.TaxExclusiveAmount) AS TotalexTax
, SUM(MYOBsalesLines.TaxExclusiveAmount)
- SUM
(
COALESCE(cast(MYOBJobsShippingTotals.TaxExclusiveAmount AS Decimal(18,2)), 0)
+ COALESCE(MYOBsalesLines.CostOfGoodsSoldAmount,0)
+ COALESCE
(
COALESCE
(
CASE
WHEN LEFT(MYOBItems.ItemNumber,5) = '31-63' THEN (136*MYOBsalesLines.Qty/1000)
WHEN LEFT(MYOBItems.ItemNumber,6) = '34S-63' THEN (200*MYOBsalesLines.Qty/1000)
ELSE 0
END
, 0
)
+ COALESCE
(
CASE
WHEN LEFT(MYOBItems.ItemNumber,5) = '34-63' THEN (250*MYOBsalesLines.Qty/1000)
WHEN LEFT(MYOBItems.ItemNumber,6) = '26-63' THEN (250*MYOBsalesLines.Qty/1000)
ELSE 0
END
, 0
)
, 0
)
)
AS Margin
, MYOBCards1.Name AS SalesPerson
, MYOBSales.SalesPersonID
, MYOBSales.InvoiceStatusID
, MYOBCards.Name
, MYOBItems.ItemName
, SUM(MYOBsalesLines.Qty) AS TotalQty
, SUM(MYOBsalesLines.CostOfGoodsSoldAmount) AS TotalCOGS
, COUNT(MYOBSales.SaleID) AS NumberOfSales
, SUM(cast(MYOBJobsShippingTotals.TaxExclusiveAmount AS Decimal(18,2))) AS ShippingTotal
FROM
(
MYOBJobsShippingTotals RIGHT JOIN
(
(
(
MYOBItems INNER JOIN MYOBsalesLines
ON MYOBItems.ItemID = MYOBsalesLines.ItemID
) INNER JOIN MYOBSales ON MYOBsalesLines.SaleID = MYOBSales.SaleID
) INNER JOIN MYOBCards ON MYOBSales.CardRecordID = MYOBCards.CardRecordID
) ON MYOBJobsShippingTotals.JobID = MYOBsalesLines.JobID
) LEFT JOIN MYOBCards AS MYOBCards1 ON MYOBSales.SalesPersonID = MYOBCards1.CardRecordID
WHERE MYOBSales.Date BETWEEN ? AND ?
GROUP BY MYOBItems.ItemNumber
, MYOBCards1.Name
, MYOBSales.SalesPersonID
, MYOBSales.InvoiceStatusID
, MYOBCards.Name
, MYOBItems.ItemName
HAVING MYOBSales.InvoiceStatusID <> 'OR'
Where the two question marks are your [Forms]![MenuReports]![StartDate] and [Forms]![MenuReports]![EndDate] values.