sql select records between today date plus 16 hours - sql

I am trying to get the records between today order date plus 16 hours.
OrderDate data type is datetime
i have records in database between that period but is not showing using the below query.
For example i have the below records.
2017-03-05 10:20:30.000
2017-03-06 10:20:30.000
query should return the second record.
any suggestions to solve this issue?
SQL Query
SELECT
dbo.Areas.AreaName,
dbo.Brands.BrandName,
dbo.Orders.OrderID,
dbo.Orders.OrderStatus,
dbo.Customers.CustomerName,
dbo.Customers.CustomerID,
dbo.Customers.Phone,
dbo.Customers.Mobile,
dbo.Orders.OrderDate,
dbo.Outlets.OutletName,
dbo.Users.FirstName,
dbo.Users.LastName,
dbo.Sources.SourceName,
SUM((OrderDetails.Quantity * OrderDetails.UnitPrice)) + Orders.DeliveryCharge - ((SUM((OrderDetails.Quantity * OrderDetails.UnitPrice)) + Orders.DeliveryCharge) * Orders.Discount / 100) AS Amount,
ReceivedOrders.ReceivingDate
FROM dbo.Orders
INNER JOIN dbo.Customers
ON dbo.Orders.CustomerID = dbo.Customers.CustomerID
INNER JOIN dbo.Outlets
ON dbo.Orders.OutletID = dbo.Outlets.OutletID
INNER JOIN dbo.Users
ON dbo.Orders.UserID = dbo.Users.UserID
INNER JOIN dbo.Sources
ON dbo.Orders.SourceID = dbo.Sources.SourceID
INNER JOIN dbo.OrderDetails
ON dbo.OrderDetails.OrderID = dbo.Orders.OrderID
INNER JOIN dbo.Brands
ON dbo.Brands.BrandID = dbo.Outlets.BrandID
INNER JOIN dbo.Areas
ON dbo.Areas.AreaID = dbo.Customers.AreaID
LEFT JOIN dbo.ReceivedOrders
ON dbo.ReceivedOrders.OrderID = dbo.Orders.OrderID
WHERE BETWEEN OrderDate AND DATEADD(HOUR, 16, OrderDate) and OrderDate=GETDATE()
GROUP BY dbo.Orders.OrderID,
dbo.Orders.OrderStatus,
dbo.Customers.CustomerName,
dbo.Customers.CustomerID,
dbo.Customers.Phone,
dbo.Customers.Mobile,
dbo.Orders.OrderDate,
dbo.Outlets.OutletName,
dbo.Users.FirstName,
dbo.Users.LastName,
dbo.Sources.SourceName,
dbo.Orders.DeliveryCharge,
Orders.Discount,
dbo.Brands.BrandName,
dbo.Areas.AreaName,
ReceivedOrders.ReceivingDate
ORDER BY dbo.Orders.OrderID

Try this:
GETDATE() BETWEEN Orders.OrderDate AND DATEADD(HOUR, 16, Orders.OrderDate)

use this to get today's date instead of just getdate() which returns present time
select cast(cast(getdate() as varchar(12)) as datetime)

You can use CONVERT(VARCHAR(8),GETDATE(),112) instead of GETDATE() this will remove current time and convert the date to varchar with ISO format yyyyMMdd which doesn't need to be converted to datetime again
WHERE OrderDate BETWEEN CONVERT(VARCHAR(8),GETDATE(),112) AND DATEADD(HOUR, 16,CONVERT(VARCHAR(8),GETDATE(),112) )
Read more about sql date formats Here

Related

How to troubleshooting the Sql test queries of on-prime and synapse

I am new to ETL testing, and I am comparing the 7 and 90 days data between on-prime and synapse,
The query Was written by my lead, but He left the project.
This is my on-prime Query,
Select s.StoreNumber,
rt.Description As RecordType,
rt.IsReturn,
Sum(tm.Amount) As TotalSales,
Sum(tm.Quantity) As TotalSalesQty
From pos.Ticket t Join pos.TicketSegment ts
On t.TicketKey = ts.TicketKey
Join pos.TicketMerchandise tm
On tm.TicketKey = ts.TicketKey
And tm.TicketSegmentKey = ts.TicketSegmentKey
Join org.Store s
On t.StoreKey = s.StoreKey
Join pos.RecordType rt
On tm.RecordTypeKey = rt.RecordTypeKey
Where t.BusinessDate = Dateadd(day,-90, getdate()) and t.BusinessDate< getdate()
Group By s.StoreNumber,
rt.Description,
rt.IsReturn
UNION ALL
Select s.StoreNumber,
rt.Description As RecordType,
rt.IsReturn,
Sum(tdi.DiscountAmount) As TotalSales,
Sum(td.Quantity) As TotalSalesQty
From pos.Ticket t Join pos.TicketSegment ts
On t.TicketKey = ts.TicketKey
Join pos.TicketDiscount td
On td.TicketKey = ts.TicketKey
And td.TicketSegmentKey = ts.TicketSegmentKey
Join pos.TicketDiscountItem tdi
On tdi.TicketDiscountKey = td.TicketDiscountKey
Join org.Store s
On t.StoreKey = s.StoreKey
Join pos.RecordType rt
On td.RecordTypeKey = rt.RecordTypeKey
Where t.BusinessDate >= Dateadd(day,-90, getdate()) and t.BusinessDate < getdate()
Group By s.StoreNumber,
rt.Description,
rt.IsReturn
Order By s.StoreNumber,
rt.Description,
rt.IsReturn
This is my synapse query:
Select s.StoreNumber,
tt.TransactionType,
tt.IsReturn,
Sum(Convert(Money, f.Amount)) As TotalSales,
Sum(f.Qty) As TotalSalesQty
From fact.PrdTransaction f
Join dim.Calendar c
On f.DateID = c.DateID
Join dim.Store s
On f.StoreID = s.StoreID
Join dim.TransactionType tt
On f.TransactionTypeID = tt.TransactionTypeID
Where c.Date>= DATEADD(day,-90, getdate()) and c.Date< getDate()
Group By s.StoreNumber,
tt.TransactionType,
tt.IsReturn
Order By s.StoreNumber,
tt.TransactionType,
tt.IsReturn
When I compared both results, I got some differences for the 7 days trailing period of TotalsalesQty and 90 days trailing period is a little more different than 7 days for TotalSales and TotalSlaesQty.
I am struggling to troubleshoot the difference, where the problem is.
Please help me to troubleshoot this.

Cannot convert from varchar to date

I'm trying to make this query work but all the time it gives:
Conversion failed when converting date and/or time from character string.
I've trying make a cast like it show in the code I do not know what else to do
In line 20 there's another idea I had but didn't work either.
SELECT 'Programadas', COUNT(*)
FROM [Base100].[dbo].[HIST_MOVIMIENTO_ENCA] enca
INNER JOIN EHC_FORMATO FORMATO ON FORMATO.CodFormato=ENCA.CodFormato
INNER JOIN [a MEDICO] as medic ON enca.Medico = medic.[nĂºmero de registro]
INNER JOIN [ESPECIALIDAD] as espc ON medic.especialidad = espc.codigo
INNER JOIN EHC_EVENTODEATENCION eve on enca.NoEvento=eve.noevento
INNER JOIN [a EMPRESA/EPS] eps on eps.nit = eve.empresa
INNER JOIN H_PACIENTE_HOSPITALIZADO HOSP on HOSP.CodigoHospitalizacion=eve.nohospitalizacion
INNER JOIN [a PACIENTE] pac ON HOSP.SecuenciaIngreso = pac.[Secuencia Ingreso]
INNER JOIN H_CAMA C ON HOSP.Habitacion_Cama = C.Habitacion_Cama
INNER JOIN H_HABITACION HAB ON C.Codigo_Hab = HAB.Codigo_Hab
INNER JOIN H_CATEGORIA_HAB CHAB ON HAB.Categoria_Hab = CHAB.Codigo_Categoria
INNER JOIN EHC_ORDENESREALIZADAS ord ON enca.nofolio = ord.nofolio
INNER JOIN EHC_MOVIMIENTODETA MD on MD.nofolio = enca.NoFolio
LEFT JOIN [EHC_ORDENESREALIZADAS] ehcord ON enca.NoFolio = ehcord.nofolio
WHERE FORMATO.CodFormato = 'SPC'
--AND (SELECT CAST(CONVERT(date, CONVERT (varchar(10), MD.respuesta), 103) as date) FROM EHC_MOVIMIENTODETA MD WHERE MD.nofolio = enca.NoFolio AND MD.CodPregunta = 'SPCA2P1')
AND CONVERT(date, SUBSTRING(MD.respuesta, 1,10)) >= CAST(DATEADD(DAY, -1, GETDATE()) as date)
AND MD.CodPregunta = 'SPCA2P1'
AND ord.estado ='P'
AND ehcord.nofolio is null
What I expect it's just the count of the result I know there's no "GROUP BY" but it's ok I just want to know that could be the problem
Use TRY_COVERT it would return NULL without failing the query, so that you can do further investigation on those null returned rows:
Example:
select
TRY_CONVERT (Date, '20190821'), --Success
TRY_CONVERT (Date, '2019 Aug 21'), --Success
TRY_CONVERT (Date, '2019 -Aug- 21'), --Success
TRY_CONVERT (Date, '2019Aug/-21') -- Failed

ETL datetime to integer error code

I'm writing an ETL in visual studio 2017 and I am getting this error:
So, I can't convert datetime datatype to integer datatype.
But the problem is, my query returns an int and not a datetime datatype.
Query:
SELECT e.eventName, e.eventType, e.numberOfPersons,
(SELECT timeKey FROM StarSchema.dbo.timeDim WHERE (r.reservationDate = [DATE])) AS reservationDate,
(SELECT timeKey FROM StarSchema.dbo.timeDim AS timeDim_2 WHERE (e.eventStartDate = [DATE])) AS eventStartDate,
(SELECT timeKey FROM StarSchema.dbo.timeDim AS timeDim_1 WHERE (e.eventEndDate = [DATE])) AS eventEndDate,
contact.name, customer.company, invoices.price, invoices.invoiceId
FROM events AS e
INNER JOIN reservation AS r ON e.reservationId = r.reservationId
INNER JOIN customer ON e.customerId = customer.customerId
INNER JOIN contact ON customer.contactId = contact.contactId
INNER JOIN invoices ON e.invoiceId = invoices.invoiceId
This is the result when I run this query:
The reservationDate, eventStartDate and eventEndDate reference a key in my time dimension, as an int not a datetime.
I tried creating a view with this query and then using it in my ETL but Visual studio still processed the columns as the datetime datatype.
Any suggestions?
**EDIT: So to be clear,, my goal is to have the datatype return as an INT and not a date datatype. I need the INT to reference my time dimension.
Try it with a CAST as DATE on the inside:
SELECT e.eventName, e.eventType, e.numberOfPersons,
(SELECT CAST (timeKey AS DATE) FROM ArenAStar.dbo.timeDim WHERE
(r.reservationDate = [DATE])) AS reservationDate,
(SELECT CAST (timeKey AS DATE) FROM ArenAStar.dbo.timeDim AS timeDim_2
WHERE
(e.eventStartDate = [DATE])) AS eventStartDate,
(SELECT timeKey FROM ArenAStar.dbo.timeDim AS timeDim_1 WHERE
(e.eventEndDate = [DATE])) AS eventEndDate,
contact.name, customer.company, invoices.price, invoices.invoiceId
FROM events AS e
INNER JOIN reservation AS r ON e.reservationId = r.reservationId
INNER JOIN customer ON e.customerId = customer.customerId
INNER JOIN contact ON customer.contactId = contact.contactId
INNER JOIN invoices ON e.invoiceId = invoices.invoiceId

Getting average difference between two dates in minutes

I am trying to get avg receiving time in minutes for each outlet.
I have tow tables Orders and ReceivedOrders.
Orders
OrderID OutletID OrderDate
1 1 2017-04-10 17:04:41.000
ReceivedOrders
ReceivingID OrderID ReceivingDate
1 1 2017-04-10 17:06:31.000
i have tried the below query but its reruns zero as avg receiving time
SQL Query
SELECT Outlets.OutletName , avg(datediff(MM, Orders.OrderDate, ReceivedOrders.ReceivingDate)) as Receive
FROM dbo.Orders INNER JOIN
dbo.Outlets ON dbo.Orders.OutletID = dbo.Outlets.OutletID INNER JOIN
dbo.ReceivedOrders ON dbo.Orders.OrderID = dbo.ReceivedOrders.OrderID
group by dbo.Outlets.OutletName
Output
OutletName Receive
Outlet1 0
Use datediff with millisecond option:
select Outlets.OutletName,
avg(datediff(ms, Orders.OrderDate, ReceivedOrders.ReceivingDate)) / 60000 as Receive
from dbo.Orders
inner join dbo.Outlets on dbo.Orders.OutletID = dbo.Outlets.OutletID
inner join dbo.ReceivedOrders on dbo.Orders.OrderID = dbo.ReceivedOrders.OrderID
group by dbo.Outlets.OutletName
Your code is doing exactly what you are specifying. You are getting the date diff in months, not minutes.
When using date parts, just spell out the full name of the date part:
SELECT ol.OutletName,
avg(datediff(minute, o.OrderDate, ro.ReceivingDate)) as Receive
FROM dbo.Orders o INNER JOIN
dbo.Outlets ol
ON o.OutletID = ol.OutletID INNER JOIN
dbo.ReceivedOrders ro
ONo.OrderID = ro.OrderID
GROUP BY ol.OutletName;
The above counts minute boundaries between two values. You may want parts of minutes, in which case I would use a smaller unit. Milliseconds are definitely an option, but they can overflow pretty easily if the dates are even a few months apart. So, you might really want something more like this:
SELECT ol.OutletName,
avg(datediff(second, o.OrderDate, ro.ReceivingDate)/60.0) as minutesToReceive
FROM dbo.Orders o INNER JOIN
dbo.Outlets ol
ON o.OutletID = ol.OutletID INNER JOIN
dbo.ReceivedOrders ro
ONo.OrderID = ro.OrderID
GROUP BY ol.OutletName;
Note the use of 60.0 rather than 60 to force non-integer arithmetic.

SQL select between two dates

Hi i looking for a query that get records between two dates
Start-date should be OrderDate + 28 days
End-date should be result of Start-date + 4 days
Select query
SELECT dbo.Orders.*, dbo.Customer.* FROM dbo.Orders INNER JOIN dbo.Customer ON dbo.Orders.Cust_ID = dbo.Customer.Cust_ID
using DATEADD() fundtion
SELECT dbo.Orders.*, dbo.Customer.*
FROM dbo.Orders INNER JOIN dbo.Customer ON dbo.Orders.Cust_ID = dbo.Customer.Cust_ID
WHERE [Start-date] DATEADD(day,28,OrderDate) AND [End-date] = DATEADD(day,4,[Start-date])