SQL server date time - sql-server

I am trying to get object which its start date + start time have passed or equal to current datetime and its end date + end time hasn't pass the current datetime. I tried convert current datetime to nvarchar as all my columns are nvarchar. I also tried converting my columns to datetime type but it doesn't work too. Please help
Column:
startDate - nvarchar (dd/mm/yyyy)
startTime - nvarchar (hh:mm) 24 hr
endDate - nvarchar(dd/mm/yyyy)
endTime - nvarchar(hh:mm) 24hr
i did try to but datetime betwween startDate + startTime AND endDate +startTime,
but it doesn't seems to work :
SELECT * FROM Promo
WHERE membership = '1'
AND promoStatus = '1'
AND CONVERT(NVARCHAR, GetDate(), 101) + ' ' +
CONVERT(NVARCHAR, DATEPART(hh, GetDate())) + ':' +
RIGHT('0' + CONVERT(NVARCHAR, DATEPART(mi, GetDate())), 2) BETWEEN
startDate + ' ' + startTime
AND endDate + ' ' + endTime
i did try other method too :
SELECT * FROM Promo
WHERE membership = '1'
AND promoStatus = '1'
AND startDate + ' ' + startTime <= CONVERT(NVARCHAR, GetDate(), 101) + ' ' +
CONVERT(NVARCHAR, DATEPART(hh, GetDate())) + ':' +
RIGHT('0' + CONVERT(NVARCHAR, DATEPART(mi, GetDate())), 2)
AND endDate + ' ' + endTime >= CONVERT(NVARCHAR, GetDate(), 101) + ' ' +
CONVERT(NVARCHAR, DATEPART(hh, GetDate())) + ':' +
RIGHT('0' + CONVERT(NVARCHAR, DATEPART(mi, GetDate())), 2)

You could do it like this:
SELECT *
FROM Promo
WHERE
membership = '1'
AND promoStatus = '1'
AND CAST(CONVERT(VARCHAR(16), GETDATE(), 120) AS DATETIME) BETWEEN
CONVERT(DATETIME, #startDate, 103) + CONVERT(DATETIME, #startTime)
AND CONVERT(DATETIME, #endDate, 103) + CONVERT(DATETIME, #endTime)
This line:
CAST(CONVERT(VARCHAR(16), GETDATE(), 120) AS DATETIME)
gets the current date time up to its minutes, meaning this will strip off the seconds and milliseconds part of the GETDATE().
And this line:
CONVERT(DATETIME, #startDate, 103) + CONVERT(DATETIME, #startTime)
will combine your date and time variables to form a new DATETIME value.
Note that you could have done away with with this if you design the tables using the proper data types.

Try this
SELECT * FROM Promo
WHERE membership = '1'
AND promoStatus = '1'
AND CAST(CONVERT(VARCHAR(16), GetDate(), 120) AS DATETIME)
BETWEEN CONVERT(DATETIME, startDate + ' ' + startTime, 120)
AND CONVERT(DATETIME, endDate + ' ' + endTime, 120)

Related

Remove the time part in Datediff

This is my query:
SELECT DISTINCT
'wk ' + TRIM(CONVERT(varchar(max), DATEADD(Week, DATEDIFF(week, 0, CONVERT(VARCHAR(max), period)), -1))) [week]
FROM
ABC
GROUP BY
TRIM(CONVERT(varchar(max), DATEADD(Week, DATEDIFF(week, 0, CONVERT(VARCHAR(max), period)), -1)))
I get a result like this: wk Aug 7 2022 12:00AM
But I want this format wk Aug 7, 2022
There was an error in the answer, it always returned january, the error is fixed now
You could build your string using the datepart function
declare #period datetime = '20220807' -- getdate()
SELECT 'wk ' +
left(datename(month, #period), 3) +
' ' + convert(varchar(2), datepart(day, #period)) +
' ,' + convert(varchar(4), datepart(year, #period))
looks like this wk Aug 7 ,2022
To convert your select clause to use this,
declare #table1 table (id int, period date)
insert into #table1 (id, period) values (1, '20220807'), (2, '20211130')
SELECT 'wk ' +
left(datename(month, dateadd( week, DATEDIFF( week, 0, CONVERT(VARCHAR(12), convert(date, period))), -1)), 3) +
' ' + convert(varchar(2), datepart(day, dateadd( week, DATEDIFF( week, 0, CONVERT(VARCHAR(12), convert(date, period))), -1))) +
' ,' + convert(varchar(4), datepart(year, dateadd( week, DATEDIFF( week, 0, CONVERT(VARCHAR(12), convert(date, period))), -1)))
from #table1
it looks like this
COLUMN1
wk Aug 7 ,2022
wk Nov 28 ,2021

Convert varchar string to datetime

I am having an issue converting below to a DateTime, I am only able to get the date portion of the string. My goal is to get both the date & time.
declare #col varchar(14) = '20220602235900';
select CONVERT(datetime, CAST(#col AS varchar(8)), 121) dtimecre
Steps:
Read the documentation for CONVERT and pick the closest format to use
Do some string manipulation to get the desired format
Convert.
DECLARE #col varchar(14) = '20220602235900';
SELECT
CONVERT(date, SUBSTRING(#col,1,8), 121) [Date Component]
, CONVERT(time, SUBSTRING(#col,9,2) + ':' + SUBSTRING(#col,11,2) + ':' + SUBSTRING(#col,13,2), 8) [Time Component]
, CONVERT(datetime, SUBSTRING(#col,1,4) + '-' + SUBSTRING(#col,5,2) + '-' + SUBSTRING(#col,7,2) + ' ' + SUBSTRING(#col,9,2) + ':' + SUBSTRING(#col,11,2) + ':' + SUBSTRING(#col,13,2), 120) [DateTime Representation];
Returns:
Date Component
Time Component
DateTime Representation
2022-06-02
23:59:00.0000000
2022-06-02 23:59:00.000
And another variant with a smaller amount of SUBSTRING:
DECLARE #col varchar(14) = '20220602235900';
SELECT DateComponent = CAST(DatePartString AS DATE),
TimeComponent = CAST(TimePartString AS TIME),
DateAndTime = CAST(DatePartString + ' ' + TimePartString AS DATETIME)
FROM (VALUES(#col)) AS O (DateColumn)
CROSS APPLY (
SELECT DatePartString = LEFT(DateColumn, 8),
TimePartString = FORMAT(CAST(SUBSTRING(DateColumn, 9, 6) AS INT), '##:##:##')
) AS String;

Query is not grouping

Im filling a table and I need this table get the daily sells, but summing and counting, sells and clients by day respectively.
But is not grouping the sales by day this is the QUERY:
insert into VentaDiariaTienda(
Fecha,
VentaDia,
Tda_Codigo,
NumeroClientes,
PromedioVtaCliente,
EditName,
EditDateTime)
select
DATENAME(dw, T_Fecha) + ', ' +
cast(datepart(dd, T_Fecha) as char(2)) + ' ' +
datename(mm, T_Fecha) + ' ' +
cast(datepart(yyyy,T_Fecha) as char(4)),
sum(T_ImporteTotal/1.16),
[FolTda_Codigo],
count(T_Cliente),
sum(T_ImporteTotal/1.16)/count(T_Cliente),
'Admin',
GETDATE()
from #Tickets
group by T_Fecha,[FolTda_Codigo]
and this is the out of this query
Thanks for your replys.
You will have to "round down" the T_Fecha values to a day, so you might try to insert the following records:
SELECT
DATENAME(dw, dt) + ', ' +
DATENAME(dd, dt) + ' ' +
DATENAME(mm, dt) + ' ' +
DATENAME(yy, dt),
SUM(T_ImporteTotal)/1.16,
FolTda_Codigo,
COUNT(T_Cliente),
SUM(T_ImporteTotal)/1.16/COUNT(T_Cliente),
'Admin',
GETDATE()
FROM #Tickets
CROSS APPLY (
VALUES (DATEADD(day, DATEDIFF(day, 0, T_Fecha), 0))
) d (dt)
GROUP BY dt, FolTda_Codigo
My proposition:
You can use format function (since SQL Server 2012, else use Wolfgang Method)
Be carefull with divide by "Count" function. If you result is 0 (by example if T_Client is always null) you will have an error
Not necessary to use "outer apply" instruction in this case, group on by date and not by date and time
Something like this:
SELECT
FORMAT(T_Fecha, 'dddd, dd MMMM yyyy', 'en-US' ),
SUM(T_ImporteTotal)/1.16,
FolTda_Codigo,
COUNT(T_Cliente),
case when COUNT(T_Cliente)=0 then null else SUM(T_ImporteTotal)/1.16/COUNT(T_Cliente) end,
'Admin',
GETDATE()
FROM #Tickets
GROUP BY cast(T_Fecha as date), FolTda_Codigo
For SQL Server 2008, replace format by
DATENAME(dw, T_Fecha) + ', ' + DATENAME(dd, T_Fecha) + ' ' +
DATENAME(mm, T_Fecha) + ' ' + DATENAME(yy, T_Fecha),

Calculate Time Difference in hh:mm

I have this query but I'm not sure what function to use so I can get time difference in this "hh:mm" format. Can anybody help ?
SELECT
EI.[FirstName]+' '+EI.[LastName] [EmployeeName], [Dpt].[FullName] [Department], [Desig].[FullName] [Designation],
FirstIN = CAST(MIN([AttendanceTimeIn]) AS TIME),
LastOUT = CAST(MAX([AttendanceTimeOut]) AS TIME),
HoursSpent = DATEDIFF(HOUR, CAST(MIN(AttendanceTimeIn) AS TIME), CAST(MAX(AttendanceTimeOut) AS TIME)),
CAST(COALESCE(AttendanceTimeIn, AttendanceTimeOut) AS DATE) [Date]
FROM [HRM].[tbl_Designation] [Desig], [HRM].[tbl_Department] [Dpt], [HRM].[tbl_EmployeeInfo] [EI]
FULL OUTER JOIN [HRM].[tbl_EmployeeAttendance] [Attendance] ON [Attendance].[EmpCode] = [EI].[ID]
WHERE
[Dpt].[ID] = [EI].[DeptCode] AND [Desig].[ID] = [EI].[DesignationCode]
AND
[EI].[RecordStatusCode] != '13'
AND
CAST((GETDATE()-1) AS DATE) = CAST(ISNULL([AttendanceTimeIn], [AttendanceTimeOut]) AS Date)
GROUP BY
EI.[FirstName]+' '+EI.[LastName], [Dpt].[FullName], [Desig].[FullName], CAST(COALESCE(AttendanceTimeIn, AttendanceTimeOut) AS DATE)
Maybe you can use something like this:
declare #d1 datetime = '2018-01-11 23:40:18.010'
declare #d2 datetime = '2018-01-12 11:59:18.010'
SELECT CONVERT(VARCHAR(2),DATEPART(HOUR,#d2 - #d1)) + ':' + CONVERT(VARCHAR(2),DATEPART(MINUTE,#d2 - #d1));
If to leave out your concept of using the time for the duration, you can use a query like below:
DECLARE #d1 DATETIME
DECLARE #d2 DATETIME
SELECT #d1 = GETDATE() - 1.465, #d2 = GETDATE()
SELECT
FirstIN = #d1,
LastOUT = #d2,
HoursSpent = CAST(DATEDIFF(HOUR, #d1, #d2) AS VARCHAR) + ':' + RIGHT('0' + CAST(DATEDIFF(MINUTE, #d1, #d2) % 60 AS VARCHAR), 2)
Let's expand step by step:
declare
#start datetime = getdate(),
#end datetime = dateadd(second, getdate(), 5000)
-- datediff(hour, #start, #end) -> hour difference
-- dateadd(hour, #start, datediff(hour, #start, #end)) -> start + integer hour difference to get less-than-an-hour diff
-- datediff(minute, dateadd(hour, #start, datediff(hour, #start, #end)), #end) -> minute difference from there
select
cast(datediff(hour, #start, #end) as varchar(2))
+ ':'
+ cast(datediff(minute, dateadd(hour, #start, datediff(hour, #start, #end)), #end) as varchar(2)) as [hh:mm]

Im stuck with this DATEDIFF

Alright so I keep getting this error:
Msg 245, Level 16, State 1, Line 1
Conversion failed when converting the varchar value ' Days ' to data type int.
Below is my code.....what am I doing wrong here....I am trying to show the day, hour and minute difference...I used the CASTS in my datediff because those were different columns so I used the cast to conjoin them to make it easier to do my datediff.....
DATEDIFF(DD, checkin_datetime, CAST(txt_signoff_ml_date AS DATETIME) + CAST(txt_signoff_ml_time AS DATETIME)) + ' Days '
+ DATEDIFF(HH, checkin_datetime, CAST(txt_signoff_ml_date AS DATETIME) + CAST(txt_signoff_ml_time AS DATETIME)) + ' Hours '
+ DATEDIFF(MINUTE, checkin_datetime, CAST(txt_signoff_ml_date AS DATETIME) + CAST(txt_signoff_ml_time AS DATETIME)) + ' Minutes'
AS Time_diff2,
DateDiff function will return result in integer. And here, you are combining Integer value and string value. Therefore, you are facing type difference error.
You have to cast datediff output to varchar as mentioned below
cast(DATEDIFF(DD, checkin_datetime, CAST(txt_signoff_ml_date AS DATETIME) + CAST(txt_signoff_ml_time AS DATETIME))as varchar(50)) + ' Days '
+ cast(DATEDIFF(HH, checkin_datetime, CAST(txt_signoff_ml_date AS DATETIME) + CAST(txt_signoff_ml_time AS DATETIME))as varchar(50)) + ' Hours '
+ cast(DATEDIFF(MINUTE, checkin_datetime, CAST(txt_signoff_ml_date AS DATETIME) + CAST(txt_signoff_ml_time AS DATETIME)) as varchar(50)) + ' Minutes'
This:
DATEDIFF(DD, checkin_datetime, CAST(txt_signoff_ml_date AS DATETIME)
needs a closing bracket. That should get you started.

Resources