How to capture results when datestamp has special exception - sql-server

I'm fairly certain I can use a CASE statement in this instance, but I'm clearly not looking at this right.
In my WHERE clause, when a datestamp resides in the month of July, I need to group lump it into my results for the month of August. Here's what I'm trying, but
I'm missing the mark:
and CPTrn_DateTime = case
when datepart(month, CPTrn_DateTime) = 7 then datepart(month, CPTrn_DateTime) in (7,8)
The reason I was trying to use a CASE statement is because only for the month of July do I need those results to be associated with August results. The reason I can't do a simple date range is because I need the logic to work for all dates moving forward as time goes on.
Here's the entire query:
DECLARE #month INT
SET #month = 8
SELECT DISTINCT cp.CPTrn_Key
,ch.Chg_Ref_No
,c.Cust_Alias
,ch.Chg_Total_Units
,ch.Chg_Amount
,cp.CPTrn_DateTime
FROM PDICompany_2049_01..CP_Transactions cp(NOLOCK)
INNER JOIN PDICompany_2049_01..Customers c(NOLOCK) ON CPTrn_Cust_Key = Cust_Key
INNER JOIN PDICompany_2049_01..Products p(NOLOCK) ON cp.CPTrn_Prod_Key = Prod_Key
LEFT JOIN PDICompany_2049_01..CP_Billing_Details CPBD(NOLOCK) ON CPBd.CPBillDtl_CPTrn_Key = cp.CPTrn_Key
AND CPTrn_Cust_Key = CPBD.CPBillDtl_Cust_Key
AND CPBD.CPBillDtl_Rec_Type = 1
LEFT JOIN PDICompany_2049_01..Customer_Locations cl(NOLOCK) ON c.Cust_WhPrcNtc_Def_CustLoc_Key = cl.CustLoc_Key
AND ((CustLoc_Type & 2) <> 0)
LEFT JOIN Charges ch ON ch.Chg_Ref_No = cpbd.CPBillDtl_Invoice_No
WHERE cp.CPTrn_Tran_Type != 0
AND c.Cust_Alias = 'MONTGOMERY CRANES, LLC'
AND CPBillDtl_Invoice_No IS NOT NULL
AND CPTrn_DateTime = CASE
WHEN datepart(month, CPTrn_DateTime) = 7
THEN datepart(month, CPTrn_DateTime) IN (7,8)
ELSE datepart(month, CPTrn_DateTime) = #month
END AS 'CPTrn_DateTime'
ORDER BY 1

Doing this is a CASE expression (Case statements don't exist in T-SQL) with the DATEPART function is going to likely ruin performance.
You don't "group" in a WHERE, you do that in your GROUP By, so i'm reading through the lines, but what's wrong with "normal" date logic?
WHERE CPTrn_DateTime >= '20190701'
AND CPTrn_DateTime < '20190901'
Edit: Simple date logic is still what you are after:
DECLARE #Month int = 8,
#Year int = 2019;
DECLARE #DateStart date = DATEFROMPARTS(#Year, IIF(#Month = 8, 7, #MOnth),1);
DECLARE #DateEnd date = DATEFROMPARTS(#Year, #Month+1, 1);
SELECT ...
FROM...
WHERE CPTrn_DateTime >= #DateStart
AND CPTrn_DateTime < #DateEnd

Or you can do it all in the query:
SELECT DISTINCT cp.CPTrn_Key
,ch.Chg_Ref_No
,c.Cust_Alias
,ch.Chg_Total_Units
,ch.Chg_Amount
,cp.CPTrn_DateTime
FROM PDICompany_2049_01..CP_Transactions cp(NOLOCK)
INNER JOIN PDICompany_2049_01..Customers c(NOLOCK) ON CPTrn_Cust_Key = Cust_Key
INNER JOIN PDICompany_2049_01..Products p(NOLOCK) ON cp.CPTrn_Prod_Key = Prod_Key
LEFT JOIN PDICompany_2049_01..CP_Billing_Details CPBD(NOLOCK) ON CPBd.CPBillDtl_CPTrn_Key = cp.CPTrn_Key
AND CPTrn_Cust_Key = CPBD.CPBillDtl_Cust_Key
AND CPBD.CPBillDtl_Rec_Type = 1
LEFT JOIN PDICompany_2049_01..Customer_Locations cl(NOLOCK) ON c.Cust_WhPrcNtc_Def_CustLoc_Key = cl.CustLoc_Key
AND ((CustLoc_Type & 2) <> 0)
LEFT JOIN Charges ch ON ch.Chg_Ref_No = cpbd.CPBillDtl_Invoice_No
WHERE cp.CPTrn_Tran_Type != 0
AND c.Cust_Alias = 'MONTGOMERY CRANES, LLC'
AND CPBillDtl_Invoice_No IS NOT NULL
AND #month = case when month(CPTrn_DateTime) = 7 then 8 else month(CPTrn_DateTime) end
I believe order by 1 is superfluous.

Related

I'm having error deriving records using Case When Statement between two specific months using Month(EndofMonth) = 08 and Month (EndOfMonth) = 09?

I need to derive the records between two specific dates.
I'm having error in the "Case When" statement.
SELECT T1.BR,T1.CID
SUM(ISNULL(CASE WHEN TRNDATE BETWEEN DATEDIFF(dd, 1,(EOMDATE IN MONTH(EOMDATE)=08)) AND (EOMDATE IN MONTH(EOMDATE)=09) THEN TransactionAmount end, 0)) AS SHRAWAN
FROM
--Nesting
(SELECT TRH.BR, TRH.CID, TRH.TRNDATE, SUM(TRH.TRNAMT) AS TransactionAmount FROM T_TRNHIST TRH
LEFT JOIN T_GLLINK GLL ON GLL.BR = TRH.BR AND TRH.GLCode = GLL.Code AND GLL.CoopRep01 = 'Y' AND GLL.TableID IN ('10','30') AND TRH.AppType+'0' = GLL.TableID
LEFT JOIN T_GLCONTROL GLC ON GLC.BR = TRH.BR
LEFT JOIN T_CALENDAR C ON TRH.BR = C.BR
WHERE GLC.FINYEAR = '2018' /*#Finyear*/ AND TRH.TRNDATE BETWEEN /*#FromDate*/GLC.FinYrStartDate And GLC.FinyrEndDate/*#ToDate*/ AND TRH.APPTYPE IN ('1','3')
AND (TRH.TRNTYPE BETWEEN '101' AND '159' OR TRH.TrnType BETWEEN '301' AND '359') AND TRH.TrnType%2=1 AND TRH.TrnAmt>0
GROUP BY TRH.BR, TRH.CID, TRH.TrnDate) T1 --, T_CALENDAR C, T_GLCONTROL G
WHERE T1.CID = '000003'
GROUP BY T1.BR, T1.CID
ORDER BY T1.BR, T1.CID
The expected result would be sum of all the amounts deposited between the given parameter dates.
TRNDATE BETWEEN DATEDIFF(dd, 1,(EOMDATE IN MONTH(EOMDATE)=08)) AND (EOMDATE IN MONTH(EOMDATE)=09)

Is there a way to loop a query using a distinct list of values with the way I have written this?

I have written a query that I currently have hardcoded to filter by department. This entire query works the way I want it and I could copy/paste this query dozens of times and write all results to a temp table but I would like a simpler and more dynamic solution. Is there some way I can loop by the distinct results of FullDepartmentFacilityName from my Forecast table? I have a few other areas in this code that are also hard coded that need to be the same value.
'ABC.ALLXYZ' is what I have to hard code
====================================================
SELECT *
FROM
[clc].[ForecastTable]
WHERE
FullDepartmentFacilityName = 'ABC.ALLXYZ'
and
DateColumn = CAST(GETDATE() AS DATE)
and
(
(ROUND (PopCountForecast, 0) > (SELECT MAX(ACT.PopCountActual)
FROM
clc.ActualTable ACT
JOIN [dim].[DepartmentTable] DTD
ON DTD.DeptID = ACT.DeptId
JOIN [dim].[FacilityTable] FD
ON FD.FclID = ACT.FclID
WHERE
ACT.DateColumn >= DATEADD(DAY, -28, CAST(GETDATE() AS DATE))
and DATEPART(WEEKDAY, ACT.DateColumn) = DATEPART(WEEKDAY, GETDATE())
and CONCAT(FD.FclName,'.All',DTD.DeptName) = 'ABC.ALLXYZ'))
or
(ROUND (PopCountForecast, 0) < (SELECT MIN(ACT.PopCountActual)
FROM
clc.ActualTable ACT
JOIN [dim].[DepartmentTable] DTD
ON DTD.DeptID = ACT.DeptID
JOIN [dim].[FacilityTable] FD
ON FD.FclID = ACT.FclID
WHERE
ACT.DateColumn >= DATEADD(DAY, -28, CAST(GETDATE() AS DATE))
and DATEPART(WEEKDAY, ACT.DateColumn) = DATEPART(WEEKDAY, GETDATE())
and CONCAT(FD.FclName,'.All',DTD.DeptName) = 'ABC.ALLXYZ'))
)
Table Structure
clc.ForecastTable - this is the main table for my query. this table has one column with a concatenated facility/department name I am calling FullDepartmentFacilityName. This table has forecasted Population Counts by facility/department key by day.
Example:
FullDepartmentFacilityName PopCountForecast Date
ABC.ALLAAA 10 7/16/19
ABC.ALLBBB 5 7/16/19
ABC.ALLCCC 8 7/16/19
BCA.ALLAAA 9 7/16/19
BCA.ALLBBB 4 7/16/19
BCA.ALLCCC 9 7/16/19
"dim.DepartmentTable" - this has all department IDs and their corresponding names
"dim.FacilityTable" - this has all facility IDs and their corresponding names
"clc.ActualTable" - this table contains real data and has a facility column and department column but not a concatenated facility/department column. This is why I created one in my query.
Have you tried CROSS APPLY? You don't give the table structure, so I can only guess what the table structure.
SELECT *
FROM (
SELECT DISTINCT FullDepartmentFacilityName
FROM Forecast
) d
CROSS APPLY (
SELECT *
FROM [clc].[ForecastTable]
WHERE FullDepartmentFacilityName = d.FullDepartmentFacilityName
and DateColumn = CAST(GETDATE() AS DATE)
and (
(ROUND (PopCountForecast, 0) > (
SELECT MAX(ACT.PopCountActual)
FROM clc.ActualTable ACT
JOIN [dim].[DepartmentTable] DTD ON DTD.DeptID = ACT.DeptId
JOIN [dim].[FacilityTable] FD ON FD.FclID = ACT.FclID
WHERE ACT.DateColumn >= DATEADD(DAY, -28, CAST(GETDATE() AS DATE))
and DATEPART(WEEKDAY, ACT.DateColumn) = DATEPART(WEEKDAY, GETDATE())
and CONCAT(FD.FclName,'.All',DTD.DeptName) = 'ABC.ALLXYZ')
) or (
ROUND (PopCountForecast, 0) < (
SELECT MIN(ACT.PopCountActual)
FROM clc.ActualTable ACT
JOIN [dim].[DepartmentTable] DTD ON DTD.DeptID = ACT.DeptID
JOIN [dim].[FacilityTable] FD ON FD.FclID = ACT.FclID
WHERE ACT.DateColumn >= DATEADD(DAY, -28, CAST(GETDATE() AS DATE))
and DATEPART(WEEKDAY, ACT.DateColumn) = DATEPART(WEEKDAY, GETDATE())
and CONCAT(FD.FclName,'.All',DTD.DeptName) = 'ABC.ALLXYZ')
)
)
) c

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.

This is not permitted when the subquery follows =, !=, <, <= , >, >= or when the subquery is used as an expression in sql query

I know that this type of question is duplicate but I didnt find accurate answer of this problem. So thats why I post it.
So, my question is that when I am running the sql query in sql server at that time it shows the heading error. I find many of things but didnt work.
Here is my query,
select
trandate, shortdescr, ref as BillNo,
f.companyname, h.brnchname,
tranno, AccName,
sum(dramount) as NetAmount, sum(SGST) GstAmt,
sum(CGST) CstAmt, sum(IGST) IGstAmt, s.SeriesName
from
(select
trandate, shortdescr, ref, dramount, CompanyID,
brnchid, accountid, refaccountid, tranno, seriesid,
case
when accountid = (select top 1 gcsysdescription
from systemparameters
where gcsysvar = 'SGST')
then dramount - cramount
else 0
end as SGST,
case
when accountid = (select top 1 gcsysdescription
from systemparameters
where gcsysvar = 'CGST' )
then dramount - cramount
else 0
end as CGST,
case
when accountid = (select top 1 gcsysdescription
from systemparameters
where gcsysvar = 'IGST' )
then dramount - cramount
else 0
end as IGST,
case
when srno = 1 --=(select top 1 gcsysdescription from systemparameters where gcsysvar='IGST' )
then (select accmas.accountname
from accountdet accdet
left outer join accountmaster accmas on accmas.accountid = accdet.accountid
where accdet.srno = 1 and accdet.seriesid = 19)
end as AccName
from
accountdet) as abc
left outer join
companymaster F on abc.CompanyID = F.companyid
left outer join
brnchmst H on abc.brnchid = H.brnchid
left outer join
Accountmaster a on abc.accountid=a.accountid
left outer join
SeriesMaster s on abc.SeriesID=s.SeriesID
where
abc.companyid = 37
and abc.brnchid in (7, 9, 8, 3, 4)
and abc.seriesid = 19
and convert(varchar(10), trandate, 112) >= '20170920'
and convert(varchar(10), trandate, 112) <= '20180331'
and a.EntryType <> 'D'
and abc.dramount <> 0
group by
trandate, shortdescr, ref, f.companyname, h.brnchname, tranno, s.seriesname, AccName
Please help me to solve this issues.
Thank You.
It seems that your subquery
select accmas.accountname from accountdet accdet LEFT OUTER JOIN accountmaster accmas
ON accmas.accountid= accdet.accountid where accdet.srno = 1 and accdet.seriesid = 19
sometimes return more than one row. You should change predicates in where or add TOP(1)...ORDER BY.

Select from same column under different conditons

I need to join these two tables. I need to select occurrences where:
ex_head of_family_active = 1 AND tax_year = 2017
and also:
ex_head of_family_active = 0 AND tax_year = 2016
The first time I tried to join these two tables I got the warehouse data
dbo.tb_master_ascend AND warehouse_data.dbo.tb_master_ascend in the from clause have the same exposed names. As the query now shown below, I get a syntax error on the "where". What am I doing wrong? Thank you
use [warehouse_data]
select
parcel_number as Account,
pact_code as type,
owner_name as Owner,
case
when ex_head_of_family_active >= 1
then 'X'
else ''
end 'Head_Of_Fam'
from
warehouse_data.dbo.tb_master_ascend
inner join
warehouse_data.dbo.tb_master_ascend on parcel_number = parcel_number
where
warehouse_data.dbo.tb_master_ascend.tax_year = '2016'
and ex_head_of_family_active = 0
where
warehouse_data.dbo.tb_master_ascend.t2.tax_year = '2017'
and ex_head_of_family_active >= 1
and (eff_from_date <= getdate())
and (eff_to_date is null or eff_to_date >= getdate())
#marc_s I changed the where statements and updated my code however the filter is not working now:
use [warehouse_data]
select
wh2.parcel_number as Account
,wh2.pact_code as Class_Type
,wh2.owner_name as Owner_Name
,case when wh2.ex_head_of_family_active >= 1 then 'X'
else ''
end 'Head_Of_Fam_2017'
from warehouse_data.dbo.tb_master_ascend as WH2
left join warehouse_data.dbo.tb_master_ascend as WH1 on ((WH2.parcel_number = wh1.parcel_number)
and (WH1.tax_year = '2016')
and (WH1.ex_head_of_family_active is null))
where WH2.tax_year = '2017'
and wh2.ex_head_of_family_active >= 1
and (wh2.eff_from_date <= getdate())
and (wh2.eff_to_date is null or wh2.eff_to_date >= getdate())
I would use a CTE to get all your parcels that meet your 2016 rules.
Then join that against your 2017 rules on parcel ID.
I'm summarizing:
with cte as
(
select parcelID
from
where [2016 rules]
group by parcelID --If this isn't unique you will cartisian your results
)
select columns
from table
join cte on table.parcelid=cte.parcelID
where [2017 rules]

Resources