SQL - Joining a list of dates with observations within a date range - sql

I have a sample query below that uses GETDATE to pull the most recent estimates. The table has TWO date columns, effectiveDate and toDate. The problem? I want to pull a weekly value so I can have a time series of estimates. If I run the query now, I will end up with all the estimates as of today, but I also want to know what they were last week, the week before, etc.
Should I create a new table containing the dates that I want and then join them against the results of the query. This is where I am stuck. Thank you.
select GETDATE() as observeDate
, (select C.companyName from ciqCompany C where C.companyId = EP.companyId) as companyName
, (select EPT.periodTypeName from ciqEstimatePeriodType EPT where EPT.periodTypeId = EP.periodTypeId) as periodTypeName
, EP.fiscalYear
, EB.brokerName as brokerName
, EA.firstName+' '+EA.lastName as AnalystName
, EDND.tradingitemid
, (select DI.dataItemName from ciqdataitem DI where DI.dataitemid = EDND.dataitemid) as dataItemName
, (select EAS.accountingStandardDescription from dbo.ciqEstimateAccountingStd EAS where EAS.accountingStandardId = EDND.accountingStandardId) as AccountingStandard
, (select Cu.ISOCode from ciqCurrency Cu where Cu.currencyid = EDND.currencyid) as ISOCode
, (select EST.estimateScaleName from ciqEstimateScaleType EST where EST.estimateScaleId = EDND.estimateScaleId) as estimateScaleName
,EDND.dataItemValue,EDND.effectiveDate,EDND.isExcluded
from ciqEstimatePeriod EP
--- link estimate period table to detailed numeric data table
----------------------------------------------------------
join ciqEstimateDetailNumericData EDND
on EDND.estimatePeriodId = EP.estimatePeriodId
and GETDATE() between EDND.effectiveDate and EDND.toDate
----------------------------------------------------------
left outer join ciqEstimateBroker EB
on EB.estimateBrokerId = EDND.estimateBrokerId --- left outer join must be used if you receive any of the anonymous estimates packages
left outer join ciqEstimateAnalyst EA
on EA.estimateAnalystId = EDND.estimateAnalystId --- left outer join must be used if you receive any of the anonymous estimates packages
where EP.companyId = 112350 -- IBM
and EP.periodTypeId = 1 -- annual
and EDND.dataItemId = 21634 --- EPS Normalized (Detailed)
and EP.fiscalYear = 2010
order by 4,5,6,10

This query is complicated enough as it is - I would hate to add to it. I would probably turn it into a view or a stored proc and query from it as needed. Then you could also have, instead of just GETDATE(), a date range as input.

Related

Error getting the amount grouped by name and account number SQL Server

I have an issue on my SQL query. I tried doing two ways
With the first query I got the right amount but I lose some name descriptions
With the second I got every name descriptions but I got a lower amount.
Context: I want to get the revenue gotten between two dates.
I need the following columns from tables
Table reciboDet I need the columns CtaIngreso, ValorUnitReciboDet
Table CuentaIngreso_A the column nombrectaingreso, ctaingreso (only to create the join)
Table Recibo the columns FechaRecibo and ReciboAnulado
To get the right name descriptions I need to verify the receipt year that was in the table AvpgEnc, but when I do that a lose the amount.
First query
SELECT
ReciboDet.CtaIngreso
, SUM(ReciboDet.ValorUnitReciboDet) AS Total
, CuentaIngreso_A.NombreCtaIngreso
FROM
ReciboDet
INNER JOIN CuentaIngreso_A
ON ReciboDet.CtaIngreso = CuentaIngreso_A.CtaIngreso
WHERE
(ReciboDet.NumRecibo IN
(SELECT NumRecibo
FROM Recibo
WHERE (FechaRecibo BETWEEN '01/10/2020' AND '31/10/2020')
AND (ReciboAnulado = 0)
AND (CuentaIngreso_A.Anio = DATEPART(year, FechaRecibo))
)
)
GROUP BY
ReciboDet.CtaIngreso
, CuentaIngreso_A.NombreCtaIngreso
ORDER BY
CuentaIngreso_A.NombreCtaIngreso
Second query
SELECT
ReciboDet.CtaIngreso [cuenta],
sum(ReciboDet.ValorUnitReciboDet) [monto],
CuentaIngreso_A.NombreCtaIngreso [descripcion]
FROM
ReciboDet
inner join avpgenc
on ReciboDet.NumFactura = AvPgEnc.NumAvPg
inner join CuentaIngreso_A
on ReciboDet.CtaIngreso = CuentaIngreso_A.CtaIngreso
WHERE
(ReciboDet.NumRecibo IN
(SELECT NumRecibo
FROM Recibo
WHERE (FechaRecibo BETWEEN '01/10/2020' AND '31/10/2020')
AND (ReciboAnulado = 0)
)
AND (year(AvPgEnc.FechaVenceAvPg) = CuentaIngreso_A.Anio)
)
GROUP BY
ReciboDet.CtaIngreso
, CuentaIngreso_A.NombreCtaIngreso
ORDER BY
ReciboDet.CtaIngreso

daily incremental results on table where transaction date <= #Date parameter

specifically looking for General Leger results. This means that I can't sum up transactions for specfic dates, or cant run Between date.
to get the results for say, today I would need to query the table for all transactions <= #Today.
That said, i am tasked with running this for every single day in 2020 thus far. is there a method to do this where i dont have to manually run for each day myself?
Query example:
glo.GLValue
, Sum(UnitCR) AS 'Credit'
, Sum(UnitDR) AS 'Debit'
, sum(FirmCR) AS 'FirmCredit'
, sum(FirmDR) AS 'FirmDebit'
FROM glacct ga
inner join gldetail gd on gd.glacct = ga.AcctIndex
inner join glnatural gn on ga.glnatural = gn.GLNaturalID
inner join glunit glu on ga.glunit = glu.GLUnitID
inner join gloffice glo on ga.GLOffice = glo.GLOfficeID
WHERE gn.GLNat IN ('11001','11002','11003','11005','11007','11011','11016','11019','11020','11021','11022','11024','11025','11026','11027','11032','11033',
'11034','11035','11036','11037','11040','11041','11042','11043','11044','11050','11051','11052','11053','11190','11199','11201','11202','11203','11204',
'11205','11206','11207','11301','11603','11700','11705','11801','11802','11803','11804','11806','11807','11808','11809','11901')--,'22001')
AND gd.PostDate <= #Yesterday
GROUP BY
glo.GLValue
Create a sub-table that give the sums for each PostDate and GLValue similar to above but also grouped on PostDate, then join that to your select above, e.g.
inner join gloffice glo on ga.GLOffice = glo.GLOfficeID
inner join ( ... new grouped select here ...) gs on gs.GLValue = glo.GlValue and gs.PostDate < gd.PostDate
Now you should be able to sum the gs values:
, Sum(gs.Credit) as Credit
, Sum(gs.Debit) as Debit
etc.

Looking compare data based on dates in SQL to then run in SSRS

HI
I have created a piece of sql below to allow me to compare if a customer had stock in a previous period or not, i need to show where the customer has stock in this period and not the last period
Simply i want to be able to run a report that only lists PERIOD3 CUSTOMER1, even if i specify dates which include periods 1 - 4
PERIOD1 CUSTOMER1
PERIOD2 NULL
PERIOD3 CUSTOMER1
PERIOD4 CUSTOMER1
I dont know how in a report to only bring back PERIOD3 CUSTOMER1 data, what is the best way to do this? in an SSRS report or in the original SQL which can then be added to a SSRS report
SELECT C43.ACCOUNT15_C43,
C43.RECODATE_C43,
SNAPSHOT.WORDREF1_C43,
CUSTOMER.NADNAME,
CUSTOMER.NADPOCODE,
CUSTOMER.ATTVALFROM_T10
FROM
(
SELECT ACCOUNT15_C43,
RECODATE_C43
FROM dbo.MBC430
GROUP BY
ACCOUNT15_C43,
RECODATE_C43
) AS C43
INNER JOIN
(
SELECT dbo.MAA930.ACCOUNT15_NAD,
dbo.MAA930.NADACCNO,
dbo.MAA930.NADNAME,
dbo.MAA930.NADPOCODE,
T10.ATTVALFROM_T10
FROM dbo.MAA930
LEFT OUTER JOIN
(
SELECT ACCOUNT15_T10,
CUSTOMERLONG_T10,
ATTVALFROM_T10
FROM
dbo.MBT100
WHERE ATTRIBCODE_T10 = 'CU1'
) AS T10
ON dbo.MAA930.ACCOUNT15_NAD = T10.ACCOUNT15_T10
AND dbo.MAA930.NADACCNO = T10.CUSTOMERLONG_T10
WHERE dbo.MAA930.NADSEQNO = '999'
AND dbo.MAA930.NADTYPE = '23'
) AS CUSTOMER
ON C43.ACCOUNT15_C43 = CUSTOMER.ACCOUNT15_NAD
LEFT OUTER JOIN
(
SELECT MBC430_1.RECODATE_C43,
MBC430_1.WORDREF1_C43
FROM dbo.MBB010
INNER JOIN dbo.MBC430 AS MBC430_1
ON dbo.MBB010.PARTNO = MBC430_1.PARTNO_C43
AND dbo.MBB010.ACCOUNT15 = MBC430_1.ACCOUNT15_C43
GROUP BY
dbo.MBB010.PRE_B01,
dbo.MBB010.PARTYPE,
MBC430_1.WORDREF1_C43,
MBC430_1.RECODATE_C43
HAVING dbo.MBB010.PRE_B01 = 'T'
AND dbo.MBB010.PARTYPE = 'FG'
AND NOT MBC430_1.WORDREF1_C43 = ' '
) AS SNAPSHOT
ON CUSTOMER.NADACCNO = SNAPSHOT.WORDREF1_C43
AND C43.RECODATE_C43 = SNAPSHOT.RECODATE_C43
Thanks

How to fix "Conversion from string "August" to type 'Date' is not vaid in SSRS

SELECT
a.ItemCode,
SUM(a.NoOfApplication) AS NoOfApplication,
SUM(a.NoOfAccomplished) AS NoOfAccomplished,
SUM(a.NoOfPending) AS NoOfPending,
SUM(a.NoOfDocumentCompliance) AS NoOfDocumentCompliance,
a.[Year]
FROM
(SELECT
ItemCode,
COUNT(am.ReferenceNumber) AS NoOfApplication,
COUNT(TNA.NoOfAccomplished) AS NoOfAccomplished,
COUNT(TNP.NoOfPending) AS NoOfPending,
SUM(FDC.NoOfDocumentCompliance) AS NoOfDocumentCompliance,
DATENAME(month, ad.applicationdate) AS [Year]
FROM
AppTypes at
INNER JOIN
AssessmentMainDetails am ON at.Category = am.Category
INNER JOIN
InspectionProcesses i ON am.ReferenceNumber = i.ReferenceNo
LEFT JOIN
(SELECT
COUNT(Status) AS NoOfDocumentCompliance,
ReferenceNumber, Status
FROM
ApplicationStatus
WHERE
Status = 'For Document Compliance'
GROUP BY
ReferenceNumber, Status) AS FDC ON FDC.ReferenceNumber = i.ReferenceNo
LEFT JOIN
(SELECT
COUNT(ReferenceNo) AS NoOfAccomplished,
ReferenceNo
FROM
InspectionProcesses
WHERE
DateOfInspection <> ''
GROUP BY
ReferenceNo) AS TNA ON TNA.ReferenceNo = i.ReferenceNo
LEFT JOIN
(SELECT
COUNT(ReferenceNo) AS NoOfPending, ReferenceNo
FROM
InspectionProcesses
WHERE
DateOfInspection = ''
GROUP BY
ReferenceNo) AS TNP ON TNP.ReferenceNo = i.ReferenceNo
INNER JOIN
ApplicationDetails ad on i.ReferenceNo = ad.ReferenceNumber
INNER JOIN
Companies c on ad.CompanyId = c.CompanyID
INNER JOIN
Zones z on c.zonecode = z.zonecode
INNER JOIN
ZoneGroups zg on z.ZoneGroup = zg.ZoneGroupId
WHERE
DateOfInspection = ''
AND ad.ApplicationDate BETWEEN '2017-08-01' AND '2017-09-30'
AND zg.ZoneGroupCode = 'HO'
AND z.ZoneCode = 'VIDC'
GROUP BY
ItemCode, DATENAME(month, ad.applicationdate)) a
GROUP BY
a.ItemCode, a.[Year]
This my code, I already converted my date to get the month name. Please I need help
Look carefully. That giant derived table (a - nice meaningful name btw) has the same group by clause as the outermost query. So that means that [a] has a single row per ItemCode and datename(month, ad.applicationdate). Therefore, there is nothing to sum in your outer query since it is grouping by the same columns.
You also have the expression:
DateOfInspection = ''
which is highly suspicious based on the name of the column. What datatype is the DateOfInspection column? Doesn't sound like it should be string-based.
And lastly, the error message you posted sounds like it comes from SSRS and not sql server. Is that the case? Does your query run correctly from SSMS? Then the problem is in your report - and it would seem that you attempt to manipulate or interpret the Year column as a date (perhaps for sorting?). It also seems a bit short-sighted in your report design that your "Year" column is actually the name of a month and that your resultset does not include the year in some fashion. What happens when your data spans more than twelve months? And how do you intend to sort your report when you have month name but not month number?

Oracle SQL Distinct Clause not presenting distinct values

I have a script when I'm trying to select locations in an inventory where quantity of said location is <= 5. The query is complete, now I'm trying to do some fine tuning, and what I'm running into now is when I use the distinct clause I am still receiving duplicate records in the same column. I do know the column next to the first are unique, but I thought distinguishing distinct and one column would roll over to next related to said column.
Here is my code:
select DISTINCT bin.scannable_id as bin,
bi.bin_id as case1,
pallet.scannable_id as pallet,
-- bi.isbn as fcsku,
nvl(fs.asin,bi.isbn) as asin,
sum(bi.quantity) as quantity,
pallet.creation_date as received_date
from containers bin
join containers pallet on pallet.containing_container_id = bin.container_id
join containers case on case.containing_container_id = pallet.container_id
join bin_items bi on bi.container_id = case.container_id
left join fcskus fs on fs.fcsku = bi.isbn
where bin.scannable_id like 'R-1-T%'
and bi.quantity <= '5'
group by bin.scannable_id, pallet.scannable_id, bi.bin_id, bi.owner,bi.isbn,nvl(fs.asin,bi.isbn), pallet.creation_date
order by sum(bi.quantity);
My output, which is obviously showing duplicate records in the scannable_id column:
Correct Formatting Thanks to conrad.
select DISTINCT bin.scannable_id as bin,
pallet.scannable_id as pallet,
nvl(fs.asin,bi.isbn) as asin,
sum(bi.quantity) as quantity
from containers bin
join containers pallet on pallet.containing_container_id = bin.container_id
join containers case on case.containing_container_id = pallet.container_id
join bin_items bi on bi.container_id = case.container_id
left join fcskus fs on fs.fcsku = bi.isbn
where bin.scannable_id like 'R-1-T%'
having sum(bi.quantity) <= '5'
group by bin.scannable_id, pallet.scannable_id, nvl(fs.asin,bi.isbn), bi.quantity
order by sum(bi.quantity);
As said on the comments you dont need a DISTINCT if you have the group by statement. And format your date field because depending on your oracle client configuration it will not show you the entire date format (e.g. date time). So try with this:
select bin.scannable_id as bin,
bi.bin_id as case1,
pallet.scannable_id as pallet,
nvl(fs.asin,bi.isbn) as asin,
to_char(pallet.creation_date, 'yyyy-mm-dd') as received_date
sum(bi.quantity) as quantity,
from containers bin
join containers pallet on pallet.containing_container_id = bin.container_id
join containers case on case.containing_container_id = pallet.container_id
join bin_items bi on bi.container_id = case.container_id
left join fcskus fs on fs.fcsku = bi.isbn
where bin.scannable_id like 'R-1-T%'
and bi.quantity <= '5'
group by bin.scannable_id,
pallet.scannable_id,
bi.bin_id,
bi.owner,
bi.isbn,
nvl(fs.asin,bi.isbn),
to_char(pallet.creation_date, 'yyyy-mm-dd')
order by sum(bi.quantity);
bi.bin_id is different for each row, so you do only have distinct results in your resultset.
distinct is applied to the final visible resultset (once the to_char etc. functions are processed)
distinct is redundant if you already use a group by expression
Solution: skipp the bi.bin_id column from your select expression.
Your logic is also confusing. You want to know the SUM of all the bi.* elements. To do so you cannot group by bi.bin_id nor any field from the bi table. This is the reason why your quantity result is always 1.