ETL datetime to integer error code - sql

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

Related

Order by on a nested query

Is their a way to order this by the Time column? I am not sure how to do this. The time is the schedule and I just need it to go from the morning to the evening.
Can I just nest another select statement and use that?
Thank you.
SELECT
DoseLevel,
LastName,
FirstName,
DOB,
EMPLID,
Time,
(
SELECT v.ColorCode
FROM ABCDocumentation cd1
LEFT JOIN ABCDocumentation cd2ON cd1.ABCDocumentationID = cd2.PairID
LEFT JOIN Medicine v ON v.MedicineID = cd1.MedicineID
LEFT JOIN Manufacturers mfg ON v.MFG_Seq = mfg.MFG_Seq
WHERE cd2.ABCDocumentationID = dt.ABCDocumentationID
) AS ParentColorCode,
(
SELECT mfg.Description
FROM ABCDocumentation cd1
LEFT JOIN ABCDocumentation cd2 ON cd1.ABCDocumentationID = cd2.PairID
LEFT JOIN Medicine v ON v.MedicineID = cd1.MedicineID
LEFT JOIN Manufacturers mfg ON v.MFG_Seq = mfg.MFG_Seq
WHERE cd2.ABCDocumentationID = dt.ABCDocumentationID
) AS ParentManuDesc
FROM
(
SELECT
cd.DoseLevel,
e.LastName,
e.FirstName,
e.DOB,
cvse.EMPLID,
cvse.AdminScheduleSlotsEmployeeID,
cd.ABCDocumentationID,
cvss.Time,
cd.ModifyDate AS 'StartTime'
FROM ABCAdminSchedule cvs
LEFT JOIN ABCAdminScheduleSlots cvss ON cvs.AdminScheduleID = cvss.AdminScheduleID
LEFT JOIN ABCAdminScheduleSlotsEmployee cvse ON cvss.AdminScheduleSlotsID = cvse.AdminScheduleSlotsID
LEFT JOIN ABCDocumentation cd ON cvse.AdminScheduleSlotsEmployeeID = cd.AdminScheduleSlotsEmployeeID
LEFT JOIN Employee e ON cvse.EmplID = e.EMPLID
WHERE CAST(TIME AS Date) = CAST(GETDATE() AS Date) AND CampusID = '06'
AND cvse.AdminScheduleSlotsEmployeeID IS NOT NULL
) dt
First off, there is no need for the derived table dt, as you are not doing any further processing.
Secondly, you can combine the two correlated subqueries into one with an APPLY.
Thirdly, conversions on columns can cause performance issues, so you can change the date check to a half-open interval, converting just GETDATE().
Finally you can add at the end an ORDER BY clause to sort.
SELECT
cd.DoseLevel,
e.LastName,
e.FirstName,
e.DOB,
cvse.EMPLID,
cvss.Time,
Parent.ColorCode,
Parent.Description
FROM ABCAdminSchedule cvs
LEFT JOIN ABCAdminScheduleSlots cvss ON cvs.AdminScheduleID = cvss.AdminScheduleID
LEFT JOIN ABCAdminScheduleSlotsEmployee cvse ON cvss.AdminScheduleSlotsID = cvse.AdminScheduleSlotsID
LEFT JOIN ABCDocumentation cd ON cvse.AdminScheduleSlotsEmployeeID = cd.AdminScheduleSlotsEmployeeID
LEFT JOIN Employee e ON cvse.EmplID = e.EMPLID
OUTER APPLY
(
SELECT v.ColorCode, mfg.Description
FROM ABCDocumentation cd1
LEFT JOIN ABCDocumentation cd2ON cd1.ABCDocumentationID = cd2.PairID
LEFT JOIN Medicine v ON v.MedicineID = cd1.MedicineID
LEFT JOIN Manufacturers mfg ON v.MFG_Seq = mfg.MFG_Seq
WHERE cd2.ABCDocumentationID = dt.ABCDocumentationID
) AS Parent
WHERE TIME >= CAST(GETDATE() AS Date) AND TIME < CAST(DATEADD(day, 1, GETDATE()) AS DATE)
AND CampusID = '06'
AND cvse.AdminScheduleSlotsEmployeeID IS NOT NULL
ORDER BY TIME
please
declare #tm table (id int identity, timee time(7))
insert into #tm (timee) values ('01:05:45'),
('10:15:18'),
('14:18:59'),
('09:15:10'),
('18:19:21'),
('21:05:17')
this is a default
select * from #tm order by id
this is a, what do you need
select tm.*,
iif(tm.part_time = 1, 'morning', 'evening') m_e from (select
case
when timee between '09:00:00' and '19:00:00' then 1
else 2 end part_time,
*
from #tm) tm
order by part_time, timee

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

retrieve large amount of data from multiple tables within seconds

The following query retrieves data from multiple tables.
There is a problem, as the data increases the amount of time to retrieve the data increases too ( the number of rows has reached to 20 thousand and it takes more than a minute to show the result).
i have used stored procedure but the result was same. Any Solution ?
Select TransactionDate,
T.InvoiceNo,
T.TotalAmount,
PCost.TotalCostPrice ,
(T.TotalAmount - PCost.TotalCostPrice) as TProfit,
P.PaidAmount, P.Balance,
CONCAT(Lastname, ', ', Firstname, ' ', Middlename) as Cashier,
ISNULL(P.DiscountAmount,0),
ISNULL(P.ProfitAmount,0),
CustomerInfo
FROM [Transaction] T
INNER JOIN TransactionPayment P ON T.InvoiceNo = P.InvoiceNo
INNER JOIN Employee E ON T.EmployeeID = E.EmployeeID
LEFT OUTER JOIN (
SELECT SUM(p.CostPrice*tl.Quantity) as TotalCostPrice,
tl.InvoiceNo
FROM Product p
INNER JOIN TransactionLineItem tl ON p.ProductID = tl.ProductID
INNER JOIN [Transaction] T ON T.InvoiceNo = tl.InvoiceNo
WHERE TransactionDate >= #DateFrom AND TransactionDate <= #DateTo
GROUP BY tl.InvoiceNo
) as PCost ON PCost.InvoiceNo = T.InvoiceNo
WHERE TransactionDate >= #DateFrom AND TransactionDate <= #DateTo
Try this:
create index IX_Transaction_TransactionDate
on dbo.[Transaction] (TransactionDate, InvoiceNo);

sql select records between today date plus 16 hours

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

How to combine two select query results into one result using sp?

I'm declaring two comparison dates, I want data from both dates. I'm using left join for combined propose but this is not correct way. I'm missing some data. Instead of left join which one is best for?
result
productid FirstQty SecondQty FirstProductRevenue SecondProductRevenue
COCAK117 1 2 1370.00 1440.00
COCAK632 1 2 1125.00 2250.00
COCAK656 1 NULL 795.00 NULL
COCAK657 1 2 720.00 2090.00
COCAK775 3 1 2475.00 825.00
I'm getting data from full of first table and matching productid from second table, but I want total productid's from both the tables.
CREATE PROCEDURE [dbo].[Orders]
(
#StartDate DATETIME,
#EndDate DATETIME,
#StartDate1 DATETIME,
#EndDate1 DATETIME,
#Rowname VARCHAR(100),
#AssociateName VARCHAR(50)
)
--[Orders] '05/03/2015','05/03/2015','05/05/2015','05/07/2015','Most Gifted Cakes','all'
AS BEGIN
if(#AssociateName='all')
BEGIN
----First duration for all associates-----
select t1.productid,t1.FirstQty,t2.SecondQty,t1.FirstProductRevenue,t2.SecondProductRevenue
from
(select op.Productid
, count(op.ProductId)as FirstQty
, Round(Sum(op.Price*op.Quantity),0) as FirstProductRevenue
from Orderdetails od
inner join (select Distinct Orderid,productid,Price,Quantity from Orderproducts) op on op.Orderid=od.Orderid
inner JOIN City ct ON od.RecipientCityName = ct.CityName
INNER JOIN Associates ass ON Ct.AssociateId = ass.AssociateId
Inner join HomepageRowWiseProducts hr on op.ProductId=hr.Productid
where Convert(datetime,Convert(Varchar(50),od.DeliveryDate,101)) between #StartDate and #EndDate
and (od.TransactionId IS NOT NULL or ltrim(od.TransactionId) != '')
and #Rowname=hr.HomepageRow_name and hr.status=1
Group by op.Productid
) t1
----Second duration for all associates-----
left join
(select op.Productid
, count(op.ProductId)as SecondQty
, Round(Sum(op.Price*op.Quantity),0) as SecondProductRevenue
from Orderdetails od
inner join (select Distinct Orderid,productid,Price,Quantity from Orderproducts) op on op.Orderid=od.Orderid
inner JOIN City ct ON od.RecipientCityName = ct.CityName
INNER JOIN Associates ass ON Ct.AssociateId = ass.AssociateId
Inner join HomepageRowWiseProducts hr on op.ProductId=hr.Productid
where Convert(datetime,Convert(Varchar(50),od.DeliveryDate,101)) between #StartDate1 and #EndDate1
and (od.TransactionId IS NOT NULL or ltrim(od.TransactionId) != '')
and #Rowname=hr.HomepageRow_name and hr.status=1
Group by op.Productid
) t2 on t1.productid=t2.productid
END
You can try to get all data at once and then sum only date ranges that you want.
I could made some mistake here as I don't have your data structures.
However you should get the idea how you can implement it.
select op.Productid
, sum( case when Convert(datetime,Convert(Varchar(50),od.DeliveryDate,101)) between #StartDate and #EndDate then
1 else 0 end) FirstQty
, sum( case when Convert(datetime,Convert(Varchar(50),od.DeliveryDate,101)) between #StartDate1 and #EndDate1 then
1 else 0 end) SecondQty,
, Round(Sum( case when Convert(datetime,Convert(Varchar(50),od.DeliveryDate,101)) between #StartDate and #EndDate
then op.Price*op.Quantity
else 0 end),0) as FirstProductRevenue
, Round(Sum( case when Convert(datetime,Convert(Varchar(50),od.DeliveryDate,101)) between #StartDate1 and #EndDate1
then op.Price*op.Quantity
else 0 end),0) as SecondProductRevenue
from Orderdetails od
inner join (select Distinct Orderid,productid,Price,Quantity from Orderproducts) op on op.Orderid=od.Orderid
inner JOIN City ct ON od.RecipientCityName = ct.CityName
INNER JOIN Associates ass ON Ct.AssociateId = ass.AssociateId
Inner join HomepageRowWiseProducts hr on op.ProductId=hr.Productid
where ( Convert(datetime,Convert(Varchar(50),od.DeliveryDate,101)) between #StartDate and #EndDate
Or Convert(datetime,Convert(Varchar(50),od.DeliveryDate,101)) between #StartDate1 and #EndDate1 )
and (od.TransactionId IS NOT NULL or ltrim(od.TransactionId) != '')
and #Rowname=hr.HomepageRow_name and hr.status=1
Group by op.Productid
Maybe this (simplified):
select coalesce(t1.productid, t2.productid) as productid, t1.FirstQty, t2.SecondQty, t1.FirstProductRevenue, t2.SecondProductRevenue
from
(select ...) t1
----Second duration for all associates-----
full join
(select ...) t2 on t1.productid = t2.productid
try this
you create a function as follows
CREATE FUNCTION OrderDetails (
#StartDate DATETIME,
#EndDate DATETIME
)
RETURNS #tblList TABLE
(
orderId VARCHAR(1000)
)
AS
BEGIN
select orderid
insert into #tblList
from Orderdetails od inner JOIN City ct ON od.RecipientCityName = ct.CityName
INNER JOIN Associates ass ON Ct.AssociateId = ass.AssociateId
Inner join HomepageRowWiseProducts hr on op.ProductId=hr.Productid
and (od.TransactionId IS NOT NULL or ltrim(od.TransactionId) != '')
and #Rowname=hr.HomepageRow_name and hr.status=1
where Convert(datetime,Convert(Varchar(50),od.DeliveryDate,101)) between #StartDate and #EndDate
return
end
then call the function in your stored procedure according to the date you are passing you don't miss any records
CREATE PROCEDURE [dbo].[Orders]
(
#StartDate DATETIME,
#EndDate DATETIME,
#StartDate1 DATETIME,
#EndDate1 DATETIME,
#Rowname VARCHAR(100),
#AssociateName VARCHAR(50)
)
--[Orders] '05/03/2015','05/03/2015','05/05/2015','05/07/2015','Most Gifted Cakes','all'
AS BEGIN
if(#AssociateName='all')
BEGIN
----First duration for all associates-----
select op1.Productid
, count(op.ProductId)as FirstQty
,count(op1.ProductId)as SecondQty
, Round(Sum(op.Price*op.Quantity),0) as FirstProductRevenue
, Round(Sum(op1.Price*op1.Quantity),0) as FirstProductRevenue
from (select Distinct Orderid,productid,Price,Quantity from Orderproducts opp inner join [Your_ScemaName].[OrderDetails](#StartDate,#EndDate) od on opp.Orderid=od.Orderid ) op
inner join (select Distinct Orderid,productid,Price,Quantity from Orderproducts opp inner join [Your_ScemaName].[OrderDetails](#StartDate1,#EndDate1) od on opp.Orderid=od.Orderid ) op1
-- since 1=1 is always true you will get all data
on 1=1
Group by op.Productid
end
end