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.
I have this SQL query
SELECT
TT.RECID,
TT.TRANSDATE,
TT.DATAAREAID,
TT.SOURCERECID,
TT.SOURCEBASEAMOUNTCUR,
TT.SOURCETAXAMOUNTCUR,
TTGJAERIVA.TAXTRANSRELATIONSHIP,
TTGJAERIVA.GENERALJOURNALACCOUNTENTRY,
TTGJAERIVA.LEDGERDIMENSION,
GJAERIVA.TEXT,
GJAERIVA.LEDGERDIMENSION AS LEDGERDIMENSIONGAE,
GJAERIVA.POSTINGTYPE
FROM TAXTRANS TT
INNER MERGE JOIN TAXTRANSGENERALJOURNALACCOUNTENTRY TTGJAERIVA ON TTGJAERIVA.TAXTRANS = TT.RECID
INNER MERGE JOIN GENERALJOURNALACCOUNTENTRY GJAERIVA ON TTGJAERIVA.GENERALJOURNALACCOUNTENTRY = GJAERIVA.RECID
AND GJAERIVA.POSTINGTYPE IN( 14,236,71,41)
WHERE
(TT.TAXORIGIN <> 11 AND TT.TRANSDATE BETWEEN '2016-06-30' AND '2017-06-30') OR (TT.TAXORIGIN = 11 AND TT.TRANSDATE BETWEEN '2017-06-01' AND '2017-06-30' )
All my query is right except for WHERE clause, how can I apply where clause using Query AOT?
In this article they apply where clause but they don't explain how they do it.
Current query
Note: If something is wrong with my question please let me know what
is it. Regards
You need to add a new range to data source TaxTrans_1 - you can use field RecId, it doesn't matter. Then you can use the following value in this range:
((TaxOrigin != 11) && (TransDate >= 30\06\2016) && (TransDate <= 30\06\2017)) || ((TaxOrigin == 11) && (TransDate >= 02\06\2017) && (TransDate <= 30\06\2017))
See Axaptapedia for more details and examples.
I have the following query:
select distinct
ROW_ID = row_number() over (
order by wms_us.wms_us.rrno.rrdate
, wms_us.wms_us.rrno.pono
, wms_us.wms_us.transferboxdet.meidhex
, att.Date_cleared
)
, ATT_PO = wms_us.wms_us.rrno.pono
, Received_Date = wms_us.wms_us.rrno.rrdate
, IMEI = case
when len(wms_us.wms_us.transferboxdet.meidhex) >= 15
then left(wms_us.wms_us.transferboxdet.meidhex, 14)
else wms_us.wms_us.transferboxdet.meidhex
end
, Model = case
when (wms_us.wms_us.model.modeldesc = 'MIXED')
then wms_us.wms_us.transferboxdet.basemodel
else wms_us.wms_us.model.modelbase
end
, Date_cleared = case
when (Future.[Error Code] = '1')
then Future.LocalTime
else att.Date_cleared
end
, Result = case
when (Future.[Error Code] = '1')
then 'PASS'
else att.Result
end
from wms_us.wms_us.transferboxdoc
inner join wms_us.wms_us.transferboxdet
on wms_us.wms_us.transferboxdoc.transferboxdocid
= wms_us.wms_us.transferboxdet.transferboxdocid
inner join wms_us.wms_us.rrno
on wms_us.wms_us.transferboxdet.rrnoid = wms_us.wms_us.rrno.rrnoid
inner join wms_us.wms_us.model
on wms_us.wms_us.transferboxdoc.modelid = wms_us.wms_us.model.modelid
left join DRSCSQLQADB01.att_view2.dbo.attview2 as att
on att.IMEI = LEFT(wms_us.wms_us.transferboxdet.meidhex, 14)
inner join Futerdial.dbo.Futuredial_Validation as Future
on Future.IMEI = wms_us.wms_us.transferboxdet.meidhex
where (wms_us.wms_us.rrno.rrdate > '2016-12-01')
and Future.IMEI = '352130070643357'
I have the IMEI in the table Futuredial_Validation duplicate, I have been trying to use the Distinct just to show me one IMEI but it's not working, there is any alternative that I can use?? Or I am using it wrong?
Attach a picture of what is showing me, I just one be able to see one the first one.
Screenshot
Thanks
For rows to be filtered out by distinct, all values must be the same. In this query it looks like you can just wrap the query in a CTE and filter on ROW_ID = 1.
I have a view in SQL and I need to get an if function in there, below is my statement.
SELECT TOP (100) PERCENT
dbo.SorDetail.MLineShipDate,
dbo.SorMaster.SalesOrder,
dbo.SorDetail.SalesOrderLine,
dbo.SorMaster.CustomerPoNumber,
dbo.SorMaster.Customer,
dbo.ArCustomer.Name AS CustomerName,
dbo.SorMaster.Salesperson,
dbo.InvMaster.StockCode,
dbo.InvMaster.Description,
dbo.InvMaster.ProductClass,
dbo.ShortOrderOrigOrderQty.OrderUom,
dbo.ShortOrderOrigOrderQty.OrderQty AS OrderQtyOrig,
dbo.ShortOrderOrigOrderQty.LineValue AS LineValueOrig,
ISNULL(dbo.ShortOrderTrimQty.TrimQty, 0) AS OrderQtyTrim,
dbo.SorDetail.MPrice * ISNULL(dbo.ShortOrderTrimQty.TrimQty, 0) AS LineValueTrim,
dbo.SorDetail.MOrderQty AS OrderQtyCurrent,
dbo.SorDetail.MPrice * dbo.SorDetail.MOrderQty AS LineValueCurrent,
dbo.ShortInvoiced.QtyInvoiced AS OrderQtyPicked,
ISNULL(dbo.ShortOrderPicked.NetSalesValue, 0) AS LineValuePicked,
ISNULL(dbo.ShortInvoiced.QtyInvoiced, 0) / dbo.ShortOrderOrigOrderQty.OrderQty * 100 AS [InFull%],
ISNULL(dbo.ShortInvoiced.QtyInvoiced, 0) / dbo.SorDetail.MOrderQty * 100 AS [StockAvailability%],
dbo.SorDetail.MWarehouse,
dbo.SorDetail.MStockDes,
dbo.SorMaster.OrderStatus,
dbo.SorMaster.InterWhSale
FROM dbo.ShortOrderTrimQty
RIGHT OUTER JOIN dbo.SorMaster
INNER JOIN dbo.ShortInvoiced ON dbo.SorMaster.SalesOrder = dbo.ShortInvoiced.SalesOrder
RIGHT OUTER JOIN dbo.SorDetail ON dbo.ShortInvoiced.SalesOrderLine = dbo.SorDetail.SalesOrderLine
AND dbo.ShortInvoiced.SalesOrder = dbo.SorDetail.SalesOrder
AND dbo.SorMaster.SalesOrder = dbo.SorDetail.SalesOrder
LEFT OUTER JOIN dbo.ShortOrderPicked ON dbo.SorDetail.SalesOrderLine = dbo.ShortOrderPicked.SalesOrderLine
AND dbo.SorDetail.SalesOrder = dbo.ShortOrderPicked.SalesOrder
ON dbo.ShortOrderTrimQty.SalesOrderLine = dbo.SorDetail.SalesOrderInitLine
AND dbo.ShortOrderTrimQty.SalesOrder = dbo.SorDetail.SalesOrder
LEFT OUTER JOIN dbo.ShortOrderOrigOrderQty ON dbo.SorDetail.SalesOrderInitLine = dbo.ShortOrderOrigOrderQty.SalesOrderLine
AND dbo.SorDetail.SalesOrder = dbo.ShortOrderOrigOrderQty.SalesOrder
LEFT OUTER JOIN dbo.InvMaster ON dbo.SorDetail.MStockCode = dbo.InvMaster.StockCode
LEFT OUTER JOIN dbo.InvCustProdType ON dbo.SorDetail.MStockCode = dbo.InvCustProdType.KeyField
LEFT OUTER JOIN dbo.ArCustomer ON dbo.SorMaster.Customer = dbo.ArCustomer.Customer
WHERE (dbo.SorDetail.LineType = '1')
AND (dbo.SorMaster.OrderStatus <> '*')
AND (dbo.SorMaster.DocumentType IN ('B', 'O'))
AND (dbo.SorMaster.Customer <> 'FAC002')
AND (dbo.SorMaster.OrderStatus <> '\')
ORDER BY dbo.SorMaster.SalesOrder, dbo.SorDetail.SalesOrderLine
Okay so I need the IF statement to do the following:
IF (IntWhSales = Y, then OrderQtyOrig = OrderQtyCurrent) else OrderQtyOrig
PLEASE help me
The equivalent IF statement in SQL for your request is:
CASE
WHEN IntWhSales = 'Y'
THEN OrderQtyCurrent
ELSE OrderQtyOrig
END
You just plug this code into the SELECT part of your query.
SELECT TOP (100) PERCENT dbo.SorDetail.MLineShipDate
, dbo.SorMaster.SalesOrder
, dbo.SorDetail.SalesOrderLine
, dbo.SorMaster.CustomerPoNumber
, dbo.SorMaster.Customer
...
, CASE
WHEN IntWhSales = 'Y'
THEN OrderQtyCurrent
ELSE OrderQtyOrig
END AS [OrderQuantity]
FROM dbo.ShortOrderTrimQty
RIGHT OUTER JOIN dbo.SorMaster
...
Add this to your select statement:
Case IntWhSales = 'Y' Then OrderQtyCurrent Else OrderQtyOrig End AS [OrderQuantity]
SELECT
A.AccID,
ISNULL(A.Camt, 0) AS Camt,
ISNULL(B.Damt, 0) AS Damt
FROM (
SELECT SUM(J.Amount) AS Camt,
J.AccID
FROM dbo.Journal AS J
INNER JOIN dbo.Voucher AS V ON J.Vid = V.Vid
WHERE
J.DRCR = 'D' AND
AccID = 1200181
GROUP BY J.AccID
) AS A
FULL JOIN (
SELECT SUM(J.Amount) AS Damt,
J.AccID
FROM dbo.Journal AS J
INNER JOIN dbo.Voucher AS V ON J.Vid = V.Vid
WHERE
J.DRCR = 'C' AND
AccID = 1200181
GROUP BY J.AccID
) AS B ON A.AccID = B.AccID
this return nothing when sub-query A or sub-query B is Empty.
i want to return if any table have data. is it possible?
As stated in the comments, I believe your answer is within a wrong assumption of your data. Nevertheless, wouldn't the following query give you the result you're looking for (given the data is correct)?
SELECT SUM(CASE WHEN J.DRCR = 'D' THEN J.Amount END) AS Damt,
SUM(CASE WHEN J.DRCR = 'C' THEN J.Amount END) AS Camt,
J.AccID
FROM dbo.Journal AS J
--INNER JOIN dbo.Voucher AS V ON J.Vid = V.Vid
WHERE j.AccID = 1200181
GROUP BY J.AccID
HAVING SUM(CASE WHEN J.DRCR IN ('D','C') THEN J.Amount END) > 0
Notice the commented table, I didn't see any use for it in your existing query. The only function might be to filter rows from Journal which do not match Voucher.