I am trying to find the list of specific job # from load date in our database with the specific condition and I have to use inner join as well.
i want to have last 15 days worth of Job # in my store procedure.
How do I set up the LoadDate that will change auto for last 15 days only.
Here is my query:
select pr.Job_Number,
Count(ItemCode1) as [Total Records],
si.PackageComplete
from
processed_record pr
inner join scanner_2 si on pr.ItemCode1 = si.ItemCode1
where
pr.Format_Name like '%Lin%' and pr.LoadDate >= '03/01/2016'
group by
pr.Job_Number, si.PackageComplete
order by
si.PackageComplete, pr.Job_Number
Your query should be as follow:
select pr.Job_Number,
Count(ItemCode1) as [Total Records],
si.PackageComplete
from
processed_record pr
inner join scanner_2 si on pr.ItemCode1 = si.ItemCode1
where
pr.Format_Name like '%Lin%' and pr.LoadDate >= DATEADD(DAY,-15,GETDATE())
group by
pr.Job_Number, si.PackageComplete
order by
si.PackageComplete, pr.Job_Number
GETDATE() will get the current date and DATEADD() function will add (subtract) -15 days.
You could use
CONVERT(date, DATEADD(DAY, -15, GETDATE()))
insted your fix Date Value.
With this code you recieve the current Date GetDate() and substract 15 Days DateAdd(day, -15, DateValue)
Finaly you Convert it into Date Typ Convert(date, value) otherwise you would get the current time, too.
Related
I am trying to update (using Inner joins for three tables) item stats STAT for table IM_ITEM by highlighting items that sold less than 12 as "D" (Discontinue).
The 2nd table PS_TKT_HIST_LIN has the Quantity sold column QTY_SOLD for each item on each day and the date column BUS_DAT.
I also need a third table IM_INV to filter the data, I need to say the last received date LST_RECV_DAT for these items is earlier than "2019-01-01" and last sales date LST_SAL_DAT is after "2019-01-01". I used the following code
UPDATE M
SET M.STAT = 'D'
FROM
dbo.IM_ITEM AS M
INNER JOIN
IM_INV AS N
ON
M.ITEM_NO = N.ITEM_NO
INNER JOIN
dbo.PS_TKT_HIST_LIN S`
ON
M.ITEM_NO = S.ITEM_NO
WHERE
CONVERT(DATETIME, FLOOR(CONVERT(FLOAT, N.LST_RECV_DAT))) <= '2019-01-01'
AND CONVERT(DATETIME, FLOOR(CONVERT(FLOAT, N.LST_SAL_DAT))) >= '2019-01-01'
AND M.STAT = 'A'
AND SUM(case when DATEPART(YYYY, (BUS_DAT)) = DATEPART(YYYY, DATEADD(YYYY, -1, getdate()))
AND DATEPART(yyyy, (BUS_DAT)) = DATEPART(yyyy, DATEADD(YYYY, -1, getdate()))
then qty_sold else 0)<12
It comes with an error
Any advise please
You should use HAVING clause instead of Sum in where.
You can use CTE to achieve the value, then update accordingly.
;with cte as(
select ITEM_NO, ..
from ..
group by ITEM_NO
having .. < 12
)
update M
set SET M.STAT = 'D'
from dbo.IM_ITEM AS M
inner join cte on M.ITEM_NO = cte.ITEM_NO
You can't use an aggregate function in where clause unless defined under subquery.
I need to calculate the datediff from one column where the in time marked with a 1 and the out time marked with a 2. if an employee swiped in and there is no out or out but there was no in i would like it to show as null.
I am not sure how I go about doing this.
SELECT
u.userid
,et.name
,CASE
WHEN scs.FullName is NULL THEN u.name
WHEN scs.FullName is NOT NULL THEN scs.FullName
END AS name
,e.LoggedTime AS SwipeTime
,CASE
WHEN et.name = 'Output On By Door' OR et.name = 'User Granted
Entry To Door Using Reading Device' THEN 1
ELSE 2
END AS SwipeTimeDiff
,d.name AS Door
FROM [Users] AS u
LEFT JOIN [Events] AS e ON e.RecordIndex1=u.UserID
LEFT JOIN [EventTypes] AS et on e.EventTypeID = et.EventTypeID
join .[Doors] AS d ON e.RecordIndex2 = d.DoorID
LEFT join SecurityContractorSignIn as scs on scs.Badge = u.lastname
WHERE LoggedTime > CONVERT(DATE, GETDATE()) and d.doorid in (32, 50, 42, 51, 33)
ORDER BY u.name,e.LoggedTime DESC
I would like to have a computed column with the time difference in days, hours and minutes or null if if there is a missing in(1) or out(2) time.
Well, the DATEDIFF() function is fully explained here and the difference for the specific datepart you want to extract is returned as an integer.
According to your need you may do something like but you will have the information in three (or more - if you want to extend) different columns:
-- Calculate the difference of how many days have passed
SELECT DATEDIFF(DAY, LoginTime, LogoutTime) AS DaysPassed
-- Calculate the difference of how many hours have passed
SELECT DATEDIFF(HOUR, LoginTime, LogoutTime) AS HoursPassed
-- Calculate the difference of how minutes have passed
SELECT DATEDIFF(MINUTE, LoginTime, LogoutTime) AS MinutesPassed
If you want to return a string whether the employee logged out or not you may use something like:
SELECT ISNULL(CONVERT(nvarchar(50), DATEDIFF(MONTH, '2019-01-04', NULL)), 'No logout')
I am working on a project for an organisation which handles tickets. I am doing this with SQL Management Studio. They want to know how much time they spend for each customer per month. What I have at the moment is individual tickets for each customer. Somehow I need to add these values by month an show in seperate column.
The column EndTime has the total time spend for each ticket, now I want to add these values for each month.
SELECT
[dbo].[Company].Name as CompanyName
, convert(time(0), CAST(EndTime AS TIME)) AS 'Worked hours'
,EndTime
,Category.Name as CategoryName
FROM [plugin.tickets].[Ticket]
LEFT JOIN [dbo].Category ON Category.Id = [plugin.tickets].Ticket.CategoryId
LEFT JOIN [plugin.tickets].TicketActivity ON TicketActivity.TicketId = [plugin.tickets].Ticket.Id
LEFT JOIN [dbo].Activity ON Activity.Id = [TicketActivity].ActivityId
LEFT JOIN [dbo].Company ON Company.Id = [plugin.tickets].Ticket.CompanyId
where
[plugin.tickets].[Ticket].status <= 2
AND [plugin.tickets].[Ticket].TypeId = 6 or [plugin.tickets].[Ticket].TypeId = 11
AND [dbo].Category.Name != 'VoIP Telefoni' AND [dbo].Category.Name != 'Beheer'
-- AND [dbo].Activity.EndTime is not null
-- AND DATEDIFF(MINUTE, CAST('00:00:00' AS TIME), CAST(EndTime AS TIME)) > 0
GROUP BY
[dbo].[Company].Name
,EndTime
,EndTime
,Category.Name
ORDER BY
'Worked hours' desc
I have a view that returns this result.
I want to sum the amounts where dateValidite is great then a certain end of month (that changes)
For example last day of month is '2016/01/31' so I will sum all the amounts (MontantAuto) where DateValidite > last day of month
I'm using this query but this sum I get is incorrect
select
a.Monnaie
, a.Category
, a.Personne
, EOMONTH(DATEADD(mm,-1,a.DateValidite)) as Previous
, sum(b.MontantAuto) As mnt
from
olap.tf_autorisation_balance a
inner join
olap.tf_autorisation_balance b on a.Id = B.Id
where
EOMONTH(DATEADD(mm,-1,a.DateValidite)) < b.DateValidite
group by
a.Monnaie, a.Category, a.Personne, a.DateValidite
Change your request as :
where EOMONTH(DATEADD(mm,-1,a.DateValidite)) < CONVERT(VARCHAR(10), b.DateValidite, 103)
I have a stored procedure that needs to return a weekly schedule of items being made on different days. It takes in a start date.
#StartDate DATETIME
Based on the startdate passed in, I need to return all the rows of data for that week, with the week starting on Tuesday and ending the following Monday.
Only taking in a startdate, how do I set the start of the week to Tuesday and then have my query return data from that particular week's range?
I know NOTHING of date functions in SQL.
I did see you can set DATEFIRST as 2 (which I think is Tuesday), but I don't know how to take in the date and find that week. I assume I need two variables to set the beginning of the week date and the end of the week date and return data in that range?
Here's my query that currently only returns the current date passed in:
SELECT
PS.ProductionDate,
L.Name,
S.Name,
PS.PartNo,
--PM.DisplayName,
PS.LotNo,
WC.Name,
WC2.Name,
PSS.Name,
PS.Mixing,
PS.Glazing,
PS.StartTime,
PS.[Weight],
PS.Pallets
FROM PROD_ProductionSchedule PS
--LEFT OUTER JOIN PartMaster PM on PS.PartNo = PM.Name
LEFT OUTER JOIN Location L on PS.LocationId = L.Id
LEFT OUTER JOIN PROD_Shifts S on PS.ShiftId = S.Id
LEFT OUTER JOIN PROD_WorkCenters WC on PS.OvenId = WC.Id
LEFT OUTER JOIN PROD_WorkCenters WC2 on PS.LineId = WC2.Id
LEFT OUTER JOIN PROD_ProductionScheduleStatus PSS ON PS.ScheduleStatusId = PSS.Id
WHERE PS.ProductionDate=#StartDate
AND PS.LocationId = CASE WHEN #Location = -1 THEN PS.LocationId ELSE #Location END
AND PS.PartNo = CASE WHEN #PartNo = 'ALL' THEN PS.PartNo ELSE #PartNo END
Get the Tuesday of the current week and 7 days later:
select dateadd(dd, 3 - datepart(dw, getdate()),
getdate()), dateadd(dd, 10 - datepart(dw, getdate()), getdate())
Calculate the beginning and end of the week:
declare #StartOfWeek datetime
declare #EndOfWeek datetime
if DATEPART(weekday,#StartDate) = 3 --Tuesday
begin
set #StartOfWeek = #StartDate
set #EndOfWeek = dateadd(week,1,#StartDate)
end
else if DATEPART(weekday,#startdate) > 3
begin
set #StartOfWeek = dateadd(DAY,-(DATEPART(weekday,#startdate)-3),#StartDate)
set #EndOfWeek = dateadd(DAY,10-DATEPART(weekday,#startdate),#StartDate)
end
else
begin
set #StartOfWeek = dateadd(DAY,-4-(DATEPART(weekday,#startdate)),#StartDate)
set #EndOfWeek = dateadd(DAY,3-DATEPART(weekday,#startdate),#StartDate)
end
Then you can use these in your Where clause:
WHERE PS.ProductionDate between #StartOfWeek and #EndOfWeek
First, create a calendar table with two columns that contain the first and last days of the working week for any given date. Then you can write some very clear, simple code:
declare #FirstDayOfWorkingWeek date,
#LastDayOfWorkingWeek date
select
#FirstDayOfWorkingWeek = FirstDayOfWorkingWeek,
#LastDayOfWorkingWeek = LastDayOfWorkingWeek
from
dbo.Calendar
where
[Date] = #StartDate
select *
from dbo.PROD_ProductionSchedule
where ProductionDate between #FirstDayOfWorkingWeek and #LastDayOfWorkingWeek
And depending on how you store your dates, be aware of the potential issues with using BETWEEN.
Using a calendar table is almost always preferable to using functions for date calculations because you can read and verify the dates easily; you can UPDATE your table to handle exceptions to the regular logic; your code is usually much more readable and easier to maintain; and performance can be better if you JOIN on a table rather than use nested functions.