SQL Server 2008 UTC Conversion to EST - sql

I need to convert one date column hat the in the database dates are off by exactly 5 hours.the time is kept as UTC and when they one views it app it displays the EST time zone. The app converts the time automatically. UTC is ahead of Eastern Standard Time by 5 . The following code seems to fix the time and day for most timestamps however , is there a way to set and offset ? The report looks at one day back and should return the converted UTC to EST times.
SELECT DISTINCT
Encounters.EncounterNo, MedicalRecords.MedRecNo as MRN,
DATEADD(DAY, -1, DATEADD(hh, DATEDIFF(hh, GETDATE(), GETUTCDATE()), Documents.CreateDateTime)) AS [Create Date],
SUBSTRING(Enrollees.EnrolleeName, 1, CHARINDEX(',', Enrollees.EnrolleeName) - 1) as [Last Name],
SUBSTRING(Enrollees.EnrolleeName, CHARINDEX(',', Enrollees.EnrolleeName) + 1, len(Enrollees.EnrolleeName)) as [First Name],
DocTypes.DocTypeName,
CAST(Enrollees.BirthDate AS Date) AS [BIRTH DATE],
Enrollees.Gender, Enrollees.SocSecNo, Enrollees.Address,
CAST(Encounters.EncntrStartDate AS Date) AS [ADMIT DATE]
FROM
Enrollees
INNER JOIN
MedicalRecords ON Enrollees.EnrolleeOwnerId = MedicalRecords.EnrolleeOwnerId
INNER JOIN
Documents
INNER JOIN
DocTypes ON Documents.DocType = DocTypes.DocType
INNER JOIN
DocsOwners ON Documents.DocId = DocsOwners.DocId
INNER JOIN
Encounters ON DocsOwners.OwnerId = Encounters.EncntrOwnerId
ON MedicalRecords.MedRecOwnerId = Encounters.MedRecOwnerId
WHERE
Documents.DocType = '65'
AND (DATEDIFF(DD, GETUTCDATE(), Documents.CreateDateTime) = - 1)
ORDER BY
DocTypes.DocTypeName

An easy way to accomplish this is to create a caluated column and then get the report to reference this new column. This way you can keep your original data and still handle the conversion via the database.
ALTER TABLE [Your Table Name] ADD
UTC2EST AS dateadd(hh,-5,[Your current UTC datetime column])

Related

SQL query to show data only for today?

I would like to automate a query without anyone changing the date manually. I have tried "GETDATE()" to no avail. I plan to use Google Sheets script editor to automate this task.
Here's a portion of the code where we change the date manually:
Left Join
OrderType ON SalesOrder.OrderTypeID = OrderType.OrderTypeID
Left Join
Location On EventRef.LocationID = Location.LocationID
Inner Join
Client On Location.ClientID = Client.ClientID
Inner Join
RequestSource On SalesOrder.RequestSourceID = RequestSource.RequestSourceID
WHERE
EventRef.EventDateTime > '11-Oct-21 0:00:00 AM'
AND EventRef.EventDateTime < '11-Oct-21 23:59:59 PM'
AND OrderStatus.OrderStatusName <> 'Added in error'
AND OrderStatus.OrderStatusName <> 'Cancelled;
GETDATE/SYSDATETIME or GETUTCDATE/SYSUTCDATETIME or even SYSDATEIMEOFFSET (which depends on your data) is what you want and some very simply date logic:
...
WHERE EventRef.EventDateTime >= CONVERT(date, GETDATE())
AND EventRef.EventDateTime < CONVERT(date, DATEADD(DAY, 1, GETDATE()))
...

How to Format a Pivoted Time Column into HH:MM

I have created a pivot table with one of the column as 'Triage Start Time', the actual format of Triage Start time is - 01-JAN-2000 23:22, which I need to Format it as 23:22. If I format this under select statement, it is giving an error. Please help me to understand where should I give the format or convert command for Time ?
select*
from
(
select
,PFRM.FORM_RESULT_VAL
,PFRM.FORM_FIELD
,CAST(PFRM.FORM_DT_TM AS DATE) AS 'Form_date'
,P.NATIONALITY
,P.GENDER
,P.DOB
,P.AGEYEARS
,E.ENCNTR_TYPE
,DATENAME(DW, CAST(A.APPOINTMENT_DT_TM AS DATE)) DayofWeek
-- CHOOSE(DATEPART(dw, CAST(A.APPOINTMENT_DT_TM AS DATE)),'Weekday',
--'Weekday','Weekday','Weekday','Weekday','WEEKEND','WEEKEND') WorkDay
FROM [ODS_CCL].[dbo].[ODS_CCL_APPOINTMENTS] A (NOLOCK)
LEFT JOIN [ODS_CCL].[dbo].[ODS_CCL_PFORMS] PFRM (NOLOCK) ON E.ENCNTR_ID=PFRM.ENCNTR_ID AND FORM_SECTION='PHCC Nursing Triage'
where A.APPOINTMENT_TYPE='Nursing Tele Triage'
) as source_table
pivot
(
max(FORM_RESULT_VAL)
for FORM_FIELD in
(
[Triage Start Time]
,[Triage End Time]
,[Triage Category]
,[Chief Complaint]
)
) as pivot_table
where Form_date>='2020-12-27' and Form_date<='2021-01-02'

Yesterday SQL Server

I know very little SQL and have been asked to fix a problem in existing code. The code is PHP but the SQL causing the problem is:
$sql = "INSERT INTO Intranet.dbo.DailyBilling (Date, JobCode, SubJob, TotalTTC, TotalATTC, CompletedBillableHours, WIP, CurrencyCode, ContractValue, Invoiced, BillableTotal, BillableToday)
SELECT
Date = CONVERT(VARCHAR(10), dateadd(day,-1, getdate()), 111),
JobCode,
vwJobValueVsInvoiced.SubJob,
TotalTTC,
TotalATTC = ATTC,
CompletedBillableHours,
WIP,
vwJobValueVsInvoiced.CurrencyCode,
ContractValue,
vwJobValueVsInvoiced.Invoiced,
BillableTotal = IIF(TotalTTC <> 0,((CompletedBillableHours/TotalTTC)*ContractValue), 0),
BillableToday = IIF(TotalTTC <> 0,
IIF(Yesterday.InvoicedYesterday <> vwJobValueVsInvoiced.Invoiced,
((CompletedBillableHours/TotalTTC)*ContractValue)-vwJobValueVsInvoiced.Invoiced ,
(((CompletedBillableHours/TotalTTC)*ContractValue)-vwJobValueVsInvoiced.Invoiced)- (Yesterday.BillableTotal-Yesterday.InvoicedYesterday)),
0)
FROM
Intranet.dbo.vwJobValueVsInvoiced
LEFT JOIN
Intranet.dbo.vwCurrentRate ON vwJobValueVsInvoiced.CurrencyCode = vwCurrentRate.CurrencyCode
LEFT JOIN
(SELECT
SubJob,
BillableTotal,
BillableToday,
InvoicedYesterday = Invoiced
FROM
Intranet.dbo.DailyBilling
WHERE
Date = CONVERT(VARCHAR(10), dateadd(day,-2, getdate()), 111)) Yesterday ON vwJobValueVsInvoiced.SubJob = Yesterday.SubJob
WHERE
vwJobValueVsInvoiced.Status <> 'Complete' AND IIF(TotalTTC <> 0,((CompletedBillableHours/TotalTTC)*ContractValue)-vwJobValueVsInvoiced.Invoiced, 0) <> 0";
The tables look like this:
dbo.dailybilling
vwJobValueVSInvoice
vwCurrencyRate
SQL returns this error:
Array ( [0] => Array ( [0] => 42S22 [SQLSTATE] => 42S22 [1] => 207 [code] => 207 [2] => [Microsoft][ODBC Driver 11 for SQL Server][SQL Server]Invalid column name 'WIP'. [message] => [Microsoft][ODBC Driver 11 for SQL Server][SQL Server]Invalid column name 'WIP'. ) )
In working through it the first question I have is What is Yesterday.InvoicedYesterday? It isn’t a table I can find and is not in the outer PHP.
Second questions, why the problem with WIP? It appears in order.
Assistance much appreciated.
Yesterday is an alias given to a subquery, and InvoicedYesterday is an alias given to a column in that subquery.
LEFT JOIN (
SELECT
SubJob
, BillableTotal
, BillableToday
, InvoicedYesterday = Invoiced
FROM Intranet.dbo.DailyBilling
WHERE Date = CONVERT(varchar(10), DATEADD(DAY, -2, GETDATE()), 111)
) Yesterday ON vwJobValueVsInvoiced.SubJob = Yesterday.SubJob
All results of that subquery in the larger query will now be referenced through that alias, so all the columns of the subquery become
Yesterday.SubJob
Yesterday.BillableTotal
Yesterday.BillableToday
Yesterday.InvoicedYesterday
If you trace Yesterday.InvoicedYesterday backwards through that query it is sourced from the table Intranet.dbo.DailyBilling and from the column [Invoiced] in that table, but the subquery is filteing data using WHERE Date = CONVERT(varchar(10), DATEADD(DAY, -2, GETDATE()), 111)
If you run this
select CONVERT(varchar(10), DATEADD(DAY, -2, GETDATE()), 111)
you will see that this is "2 days ago" or "the day before yesterday" e.g. if today is 2018-10-27 the query returns '2018/10/25' (as a string, literally in that format)
I generally would not recommend use of date style 111 in your query (it is used twice). Instead I would recommend using style number 112 instead (this has no delimiter and is the safest format to use).
Like was mentioned in the previous answer, Yesterday is an alias for the subquery and invoicedYesterday is one of its columns alias.
I think the problem with the WIP column is that it belongs to the DailyBilling table but the column is not present in the select clause from the left join named with the Yesterday alias.

How to get week formatted string in sql query

I have the following SQL query (sql server 2008):
SELECT sum(data.freq) as freq,data.week as week FROM (
SELECT
count(daterequested) as freq,
datepart(wk,daterequested) as week,
daterequested
FROM request ma
JOIN contracts mc ON (mc.uid= ma.uid)
JOIN groups og ON og.groupuid = mc.groupuid
JOIN member m ON (m.memberuid = mc.memberuid)
WHERE daterequested BETWEEN
DATEADD(MONTH,-1,GETDATE())
AND
GETDATE()
AND isdeleted = 0
GROUP BY datepart(wk,daterequested),daterequested
--ORDER BY daterequested ASC
) data
GROUP BY data.week
The result is a table with the following data:
Instead of showing the week number I would like to show the week formatted as following:
MM/dd where MM = month and dd is the day where the week starts.
It would be great if I can format starting with first day of the week, then a middle slash, then the last day of that week and finally the month: example: 11-17/04 (April 11 to 17), etc.
Here is the final table that I would like to get:
Any clue?
In case someone needs it just found a solution, maybe is not the best but works.
SELECT sum(data.freq) as freq,
data.week as week, CAST(data.weekstart as varchar) + '-' + CAST(data.weekend as varchar) + '/' + CAST(data.monthend as varchar) as formatweek
FROM (
SELECT
count(daterequested) as freq,
datepart(wk,daterequested) as week,
DATEPART(dd,DATEADD(dd, -(DATEPART(dw, daterequested)-1), daterequested)) weekstart,
DATEPART(dd,DATEADD(dd, 7-(DATEPART(dw, daterequested)), daterequested)) weekend,
DATEPART(mm,DATEADD(dd, 7-(DATEPART(dw, daterequested)), daterequested)) monthend,
daterequested
FROM requestma
JOIN contracts mc ON (mc.uid= ma.uid)
JOIN groups og ON og.groupuid = mc.groupuid
JOIN member m ON (m.memberuid = mc.memberuid)
WHERE daterequested BETWEEN
DATEADD(MONTH,-1,GETDATE())
AND
GETDATE()
AND isdeleted = 0
GROUP BY datepart(wk,daterequested),daterequested
--ORDER BY daterequested ASC
) data
GROUP BY data.week,data.weekstart,data.weekend,data.monthend

Arithmetic overflow error converting expression to data type datetime [SQL SERVER 2008 R2]

I have this query below and I keep getting an error
Arithmetic overflow error converting expression to data type datetime error
when executing. I am pretty sure it has to do with DATE_ID = etc etc, because every time I put in a timestamp in their it works. Can anyone help me ?
SELECT
Dimension.[Every 10 minutes],
COUNT(*) as [Number of Transactions],
df.[Function Name]
FROM
dbo.table, Dimension, DimensionFunction df
WHERE
DATE_ID = DATEADD(day, -1, convert(varchar(50), GETDATE(),20))
AND dbo.table.TIME = Dimension.Time
AND df.FUNCTION_CODE = dbo.table.FUNCTION_CODE
AND INTERFACE_ID = 2
AND dbo.table.FUNCTION_CODE in ('ABX', 'BBB','DDD','EEE')
AND TABLE.TIME BETWEEN '07:00' and '17:59'
GROUP BY
Dimension.[Every 10 minutes], df.[Function Name]
ORDER BY
Dimension.[Every 130 minutes], df.[Function Name]