Using MAX function for greatest value between a range - sql-server

Pretty new to tsql functions, and I'm trying to write one that returns a value for the STC_STATUS for the greatest STC_STATUS_DATE where the STC_STATUS_DATE is <= the STC_START_DATE+9. They way I have it now, it returns a null value if there is a STC_STATUS > stc_start_date+9.
SELECT #Result1 = STC_STATUS
FROM STC_STATUSES ss
LEFT OUTER JOIN STUDENT_ACAD_CRED stc ON ss.STUDENT_ACAD_CRED_ID = stc.STUDENT_ACAD_CRED_ID
WHERE ss.STUDENT_ACAD_CRED_ID = ISNULL(#student_acad_cred_id, '0')
AND MAX(ss.STC_STATUS_DATE) <= DATEADD(day,9,stc.STC_START_DATE)
Any help would be greatly appreciated.
EDIT: Sample data per recommendation:
The function returns a null value because pos 1 has a stc_status date that is greater than stc_start_date+9. What I aim to have the function do is return the most recent status date below stc_start_date+9, which would be record 2 in this sample.

you can use TOP 1 to get the correct result
SELECT TOP 1 #Result1 = STC_STATUS
FROM STC_STATUSES ss
LEFT OUTER JOIN STUDENT_ACAD_CRED stc
ON ss.STUDENT_ACAD_CRED_ID = stc.STUDENT_ACAD_CRED_ID
WHERE ss.STUDENT_ACAD_CRED_ID = ISNULL(#student_acad_cred_id, '0')
AND ss.STC_STATUS_DATE <= DATEADD(day,9,stc.STC_START_DATE)
ORDER BY ss.STC_STATUS_DATE desc

Related

SQL query is returning null values after join where there should be numeric values

I am inserting some data from an existing table into a new table. There is a specific column called DescNitro which is either returned as 0 or Null in the new table. I've checked specific cases and the Null values are replacing numeric values on the old table. Any idea why this is happening? Code below:
DECLARE #DataAtual date = '2021-11-01';
DECLARE #UltMes date = DATEADD(MONTH, -1, #DataAtual);
DECLARE #PenUltMes date = DATEADD(MONTH, -2, #DataAtual);
DECLARE #AnoUltMes integer = YEAR(#UltMes);
DECLARE #MesUltMes integer = MONTH(#UltMes);
DECLARE #AnoPenUltMes integer = YEAR(#PenUltMes);
DECLARE #MesPenUltMes integer = MONTH(#PenUltMes);
SELECT
m.datAno
,m.datMes
,m.Segmento
,m.nomDiretoria
,m.nomFilial
,m.Ov
,o.[Região] AS Filial_Pri
,m.[Cod_Rede] AS Cod_Rede
,m.Desc_Rede
,m.CodSegTatica AS cod_Canal_SAP
,m.Canal_Pricing AS cod_Canal_Pri
,m.Des_Canal_Pricing
,m.codMaterial
,m.Vol_Meta AS Vol_Meta_Ciex
,m.Fat_Meta AS Fat_Meta_Ciex
,g.[DescNitro]
INTO
[pri].[tblMetaPrecoteste]
FROM
[pri].[tblDadMetaCiex] m
LEFT JOIN
dbo.tblCadMaterial mat ON mat.codMaterial = m.codMaterial
LEFT JOIN
[pri].[tblDadOvFilial] o ON o.[Organização] = m.Ov
LEFT JOIN
[pri].[tblDadArvore] a ON a.Material = m.codMaterial
AND a.[Filial] = o.[Região]
AND a.[Canal de Vendas] = m.[Des_Canal_Pricing]
LEFT JOIN
(SELECT
t.[codMaterial],
t.[codOrganizacaoVenda],
t.[codSegTatica],
t.[codRede],
SUM(t.[DescNitro]) AS DescNitro
FROM
[MktIntelligence].[dbo].[tbl_F_PM_join_real_fifo_meta_com_gp] t
WHERE
(t.datmes = #MesUltMes AND t.datAno = #AnoUltMes)
OR (t.datmes = #MesPenUltMes AND t.datAno = #AnoPenUltMes)
GROUP BY
t.[codMaterial], t.[codOrganizacaoVenda], t.[codSegTatica], t.[codRede]) g ON m.[codMaterial] = g.[codMaterial]
AND m.[Ov] = g.[codOrganizacaoVenda]
AND m.[codSegTatica] = g.[codSegTatica]
AND m.[Cod_Rede] = g.[codRede]
Since that's a left join therefore if there is no match it will display as NULL otherwise use isnull(columnname,0) so it will display 0 when it's NULL

SQL Server : Sum function is returning wrong value

So this is my query
select a.ERSDataValues_ERSCommodity_ID,c.ersGeographyDimension_country,
b.ERSTimeDimension_Year,
sum(a.ERSDataValues_AttributeValue) as Total
from cosd.ERSDataValues a ,cosd.ERSTimeDimension_LU
b,cosd.ERSGeographyDimension_LU c
where a.ERSDataValues_ERSCommodity_ID in (SELECT
ERSBusinessLogic_InputDataSeries
FROM [AnimalProductsCoSD].[CoSD].[ERSBusinessLogic]
where ERSBusinessLogic_InputGeographyDimensionID = 7493
and ERSBusinessLogic_InputTimeDimensionValue = 'all months'
and ERSBusinessLogic_Type = 'time aggregate')
and a.ERSDataValues_ERSTimeDimension_ID = b.ERSTimeDimension_ID
and c.ersGeographyDimension_country != 'WORLD'
and a.ERSDataValues_ERSGeography_ID=c.ERSGeographyDimension_ID
group by b.ERSTimeDimension_Year,a.ERSDataValues_ERSCommodity_ID,
c.ersGeographyDimension_country
order by b.ERSTimeDimension_Year,a.ERSDataValues_ERSCommodity_ID
This is the updated query, I know it is long but I am facing the same issue the sum does not match with values when I sum up manually
It's most likely a problem with your JOINs (which you aren't technically using). Try removing the SUM and GROUP functions and see if you're getting duplicate rows (maybe limit your time frame to get fewer rows if this is a large data set):
SELECT b.TimeDimension_Year ,
c.GeographyDimension_country ,
a.DataValues_AttributeValue
FROM cosd.DataValues a ,
cosd.TimeDimension_LU b ,
cosd.GeographyDimension_LU c
WHERE a.DataValues_Commodity_ID = 2257
AND a.DataValues_TimeDimension_ID = b.TimeDimension_ID
AND c.GeographyDimension_ID = 7493
AND b.TimeDimension_Year = 2015;

Iterate through a list using SQL While Loop

I have written a SQL query that joins two tables and calculates the difference between two variables. I want a while loop iterate through the code and do the procedure for a list of organizations numbers orgnr.
Use Intra;
drop table #Tabell1
go
select Månad = A.Manad, Intrastat = A.varde, Moms = B.vardeutf
into #Tabell1
From
IntrastatFsum A
join
Momsuppg B
on A.Orgnr = B.Orgnr
where A.Orgnr = 165564845492
AND A.Ar = 2017
AND B.Ar = A.AR
--AND A.Manad = 11
AND A.Manad = B.Manad
AND A.InfUtf = 'U'
order by A.Manad
select *, Differens = (Intrastat - Moms)/ Moms from #Tabell1
Where do I put the while loop and how should I write it? I don't have a lot of experience with SQL so any help is appreciated.
wasnt clear at all when posting this question was in a big hurry, so sorry guys for that. But what im trying to do is:
This code just runs trough some data, calculates the difference in % for a special company. Each month we get a list of companies that show high standard deviation for some variables. So we have to go through them and compare the reported value with the taxreturn. What im trying to do is write a code that compares the values for "Intra" which is the reported value and " Moms" which is reported tax value. That part i have already done what i need to do now is to insert a loop into the code that goes through a list instead where i have stored the orgnr for companies that show high std for some variables.I want it to keep a list of the companies where the difference between the reported values and taxreturn is high, so i can take an extra look at them. Because sometimes the taxreturn and reported value to ous is almost the same, so i try to remove the most obvious cases with automation
I don't think you need a loop in your query.
Try changing this where-clause:
where A.Orgnr = 165564845492
To this:
where A.Orgnr in (165564845492, 123, 456, 678)
just remove A.Orgnr = 165564845492 in where clause, there is no need of loop
Use Intra;
drop table #Tabell1
go
select Månad = A.Manad, Intrastat = A.varde,Moms = B.vardeutf
into #Tabell1
From
IntrastatFsum A
join
Momsuppg B
on A.Orgnr = B.Orgnr
where A.Ar = 2017
AND B.Ar = A.AR
--AND A.Manad = 11
AND A.Manad = B.Manad
AND A.InfUtf = 'U'
order by A.Manad
select *, Differens = (Intrastat - Moms)/ Moms from #Tabell1
Question is not clear (to me)
select Månad = A.Manad, Intrastat = A.varde, Moms = B.vardeutf
, Differens = (A.varde - B.vardeutf) / B.vardeutf
From
IntrastatFsum A
join
Momsuppg B
on A.Orgnr = B.Orgnr
AND A.Orgnr in (165564845492, ...)
AND A.Ar = 2017
AND A.Manad = B.Manad
AND A.InfUtf = 'U'
order by A.Manad

SQL Query for list within select where field = value and otherfield = othervalue

I need to fudge an existing SQL Server procedure rather quickly. It's a bit of a hack job but needs must.
I need for the following to return a list of voucher codes and invoice numbers rather than just one row of data where the comment is (in the WHERE clause):
SELECT TOP 10
IH.INH_Voucher AS [ID], IH.COY_ID AS COY_ID,
IH.INH_DateSupInv AS ORD_UpdatedOn,
V.VES_ID, V.VES_IMOnumber, IH.INH_Order,
IH.INH_ID AS ORD_ID, IH.INH_INDID
FROM
InvoiceHDR IH (NOLOCK)
INNER JOIN
VESSACCOMP VA ON IH.COY_ID = VA.COY_ID
INNER JOIN
Vessel V ON VA.VES_ID = V.VES_ID
WHERE
v.VSS_ID IN ('01') AND
(IH.INH_Status >= 20 AND IH.INH_Status <= 40) AND
--IH.INH_Voucher = '170CH' AND IH.INH_SupInv = '1532' NEED LIST
IH.INH_INDID IS NOT NULL
So I would need
Voucher = '1700CH' AND SupInv = '1235' AND
Voucher = '180CH' AND SupInv = '1111' AND
And so on for many matching VoucherCodes and InvoiceCodes.
I hope this is clear?
Thanks.
You can apply the following WHERE clause to your query:::
WHERE
v.VSS_ID IN ('01') AND
(IH.INH_Status BETWEEN 20 AND 40) AND
((IH.INH_Voucher = '170CH' AND IH.INH_SupInv = '1532')
OR (IH.INH_Voucher = '180CH' AND IH.INH_SupInv = '1111'))
AND IH.INH_INDID IS NOT NULL

How to get all values including null in a SQL Server case statement?

I have a big stored procedure, and basically I want to select all values (including null) if my variable #DimBrowserId is set to 0. I am using a case statement, however this is only catching values that actually have something and ignoring the NULL valued fields. Because I am using the = clause in the WHERE I cannot do IS NULL. I do not want to have to write 2 IF statements because the stored procedure would then be enormous, so I want to know how to get null values as well. Here is my code:
SELECT
DATEPART(yy, DATEADD(mi, #Mdelta, d.DimDateValue)),
DisableCount = COUNT(*)
FROM
dbo.FactDisable AS f
JOIN
dbo.DimDate AS d ON f.DimDateId = d.DimDateId
JOIN
dbo.DimDevice AS v ON f.DimDeviceId = v.DimDeviceId
WHERE
d.DimDateValue >= #StartDateGMT
AND d.DimDateValue <= #EndDateGMT
AND f.IsTest = #IncludeTest
AND f.DimProductId = #DimProductId
AND v.DimBrowserId = CASE
WHEN #DimBrowserId = 0 THEN v.DimBrowserId
ELSE #DimBrowserId
END
GROUP BY
DATEPART(yy, DATEADD(mi, #Mdelta, d.DimDateValue))
The code is near the CASE clause.
Thanks
Change that line to be
AND (#DimBrowserID = 0 OR #DimBrowserID = v.DimBrowserId)
If #DimBroserID is 0 then no filtering will be applied for this line.
Use ISNULL:
SELECT DATEPART(yy,DATEADD(mi,#Mdelta,d.DimDateValue)),
DisableCount=COUNT(*)
FROM dbo.FactDisable AS f
JOIN dbo.DimDate AS d ON f.DimDateId = d.DimDateId
JOIN dbo.DimDevice AS v ON f.DimDeviceId = v.DimDeviceId
WHERE d.DimDateValue >= #StartDateGMT AND d.DimDateValue <= #EndDateGMT
AND f.IsTest = #IncludeTest AND f.DimProductId = #DimProductId
AND v.DimBrowserId = CASE WHEN ISNULL(#DimBrowserId,0) = 0 THEN v.DimBrowserId ELSE #DimBrowserId END
GROUP BY DATEPART(yy,DATEADD(mi,#Mdelta,d.DimDateValue))
CASE WHEN COALESCE(#MightBeNull, 0) = 0 THEN ZeroResult ...
will be treated as zero if #MightBeNull is null, and whatever #MightBeNull is if it's not null.
Assuming null means any browser, a better data model for this scenario might be to set an ID that identifies any browser, instead of setting it to null.
You probably know what you are running into is NULL does not equal NULL in a comparison.
Assuming you don't have control of the data model to fix that, one option would be to coalesce your NULL values to an unused id.
The resulting WHERE clause would look like this, assuming -1 is the unused value you choose.
AND COALESCE(v.DimBrowserId, -1) = CASE WHEN #DimBrowserId = 0 THEN COALESCE(v.DimBrowserId, -1) ELSE #DimBrowserId END

Resources