How to Format a Pivoted Time Column into HH:MM - sql

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'

Related

How to convert text to date entered as a date in sql?

Data type is TEXT and entered as '20/11/2017' and when using MAX or MIN it ignores the month. I am trying to convert it into a date format for month to be considered as well.
CAST AND CONVERT do not seem to work as the following error returns
Msg 241, Level 16, State 1, Line 13
Conversion failed when converting date and/or time from character string.
Code:
SELECT
user_id,
record_id
--CAST(onSale AS date) AS onSale
--CONVERT(DATE, onSale) AS onSale,
--CONVERT(DATE, OffSale) AS OffSale
FROM (SELECT user_id,
record_id,
(SELECT MAX(value) AS Expr1
FROM UPLOADS.LINES AS SUH WITH (NoLock, ReadUncommitted)
WHERE (field_id = 4782) AND (record_id = UR.record_id)) AS onSale,
(SELECT MAX(value) AS Expr1
FROM UPLOADS.LINES AS SUH WITH (NoLock, ReadUncommitted)
WHERE (field_id = 4783) AND (record_id = UR.record_id)) AS OffSale
FROM UPLOADS.RECORDS AS UR WITH (NoLock, ReadUncommitted)
WHERE (module_id = 18)) AS DATA;
The end result would essentially be the MAX or MIN date with all three components being date,month and year. So if the user has entered two dates being 17/05/2018 and 17/04/2018 then the first should be shown if MAX is used.
You can use a format code when using CONVERT, and you can even use TRY_CONVERT to prevent errors from invalid dates. I also improved your code to make it simpler and more efficient.
SELECT [user_id],
record_id,
MAX(CASE WHEN SUH.field_id = 4782 THEN TRY_CONVERT( DATE, SUH.value, 103) END) AS onSale,
MAX(CASE WHEN SUH.field_id = 4783 THEN TRY_CONVERT( DATE, SUH.value, 103) END) AS OffSale
FROM UPLOADS.RECORDS AS UR
JOIN UPLOADS.LINES AS SUH ON SUH.record_id = UR.record_id
WHERE module_id = 18
GROUP BY [user_id],
record_id;
This is a slight improvement on Luis's answer in terms of the SQL:
SELECT ur.[user_id], ur.record_id,
MAX(CASE WHEN SUH.field_id = 4782 THEN TRY_CONVERT( DATE, SUH.value, 103) END) AS onSale,
MAX(CASE WHEN SUH.field_id = 4783 THEN TRY_CONVERT( DATE, SUH.value, 103) END) AS OffSale
FROM UPLOADS.RECORDS UR LEFT JOIN
UPLOADS.LINES AS SUH
ON SUH.record_id = UR.record_id AND
SUH.field_id IN (4782, 4783)
WHERE ur.module_id = 18
GROUP BY ur.[user_id], ur.record_id;
That said, your problem is that your data is not in the format you think it is. Hence, the problem with type conversions. As #marc_s says in a comment, you should be using SQL native and appropriate types which in this case is DATE. And you certainly should not be using deprecated types, such as TEXT (unless you really just mean VARCHAR() and don't realize that there is a deprecated TEXT type). If you are storing values in strings (because there are different types), you should use the standard format, either YYYYMMDD or YYYY-MM-DD.
You can find these values by running:
select suh.value
from uploads.lines suh
where suh.field_id in (4782, 4783) and
try_convert(date, suh.value, 103) is null and
suh.value is not null;
This can help you fix your data.
After you have fixed your data, you can also fix the type:
update uploads.lines
set suh.value = convert(varchar(255), convert(date, suh.value, 103), 112); -- this will convert the value to the default date format

How to partially Match cell against another partial cell

I have a problem with two tables which I need to compare dates for the same reference. The problem is that
the dates are different formats and
superfluous data is also contained within both date cells.
Global
No. Date
1 1992-08-25 00:00:00.000
2 2015-05-19 00:00:00.000
3 2000-01-12 00:00:00.000
Local
No. Date
1 25.08.1992 00:00:00.000000000 GMT
1 28.08.1992 00:00:00.000000000 GMT
2 19.05.2015 00:00:00.000000000 GMT
3 12.01.2000 00:00:00.000000000 GMT
3 17.01.2000 00:00:00.000000000 GMT
Note that the date formats between the two tables differ and contain lots of time and zero data that is not needed. So ideally I would like to see the format as DD-MM-YYYY.
I would like to return only the Global and Local entries where the Local date differs from Global date. So from the data above, I would want to see:
No. Date No. Date
1 25-08-1992 1 28-08-1992
3 12-01-2000 3 17-01-2000
I would put my attempts so far, but to be honest I have no idea on how to tackle the partial cell matching and re-formatting.
Any ideas?
Update:
I tried a solution from #Sarslan and substituted my table and field names which resulted in this:
WITH G AS
(
SELECT [UPC], CONVERT(DATE,LEFT([GLOBAL RELEASE DATE], CHARINDEX(' ',
[GLOBAL RELEASE DATE])),120) [Date] FROM [dsched_migration].[emi].
[EMI_Global]
)
,L AS
(
SELECT [UPC], CONVERT(DATE,LEFT([TERR_REL_DATE], CHARINDEX(' ',
[TERR_REL_DATE])),104) [Date] FROM [dsched_migration].[emi].
[terr_release_dates]
)
SELECT
G.UPC, CONVERT(VARCHAR,G.Date,105) [GLOBAL RELEASE DATE],
L.UPC, CONVERT(VARCHAR,L.Date,105) [TERR_REL_DATE]
FROM
G INNER JOIN L ON L.UPC = G.UPC
WHERE L.Date <> G.Date
I keep getting this error:
Msg 241, Level 16, State 1, Line 7
Conversion failed when converting date and/or time from character string.
select * from
(
select a.no, to_char(a.date,'DD-mm-YYY') Date1 , b.no, to_char(b.date,'DD-mm-YYY') Date2
from Global a inner join Local b on (a.no=b.no)
)
where Date1<>Date2;
Could you try this?
;WITH G AS
(
SELECT [No], CONVERT(DATE,LEFT([Date], CHARINDEX(' ', [Date])),120) [Date] FROM [GLobal]
)
,L AS
(
SELECT [No], CONVERT(DATE,LEFT([Date], CHARINDEX(' ', [Date])),104) [Date] FROM [Local]
)
SELECT
G.No, CONVERT(VARCHAR,G.Date,105) [Date],
L.No, CONVERT(VARCHAR,L.Date,105) [Date]
FROM
G INNER JOIN L ON L.No = G.No
WHERE L.Date <> G.Date
Result
No Date No Date
----------- ------------------------------ ----------- ------------------------------
1 25-08-1992 1 28-08-1992
3 12-01-2000 3 17-01-2000
When you have some formatted string that format will never change you can simplify it like this - this will also give you more flexibility -:
;with tg as (
select [No],
-- Format is : yyyy-mm-dd
left([Date], 4) yyyy, substring([Date], 6, 2) mm, substring([Date], 9, 2) dd
from g
), tl as (
select [No],
-- Format is: dd-mm-yyyy
substring([Date], 7, 4) yyyy, substring([Date], 4, 2) mm, left([Date], 2) dd
from l
)
select *
from tg
inner join tl
on tg.[No] = tl.[No]
and not (tg.yyyy = tl.yyyy and tg.mm = tl.mm and tg.dd = tl.dd);
Thanks for all replies but found a solution:
Created a new column then ran this query to confirm the conversion:
SELECT '19.10.2009 00:00:00.000000000 GMT',
CONVERT(datetime, LEFT('19.10.2009 00:00:00.000000000 GMT',10), 104)
This gave me the right format then I ran the following query to update the new column with the formatted date:
update LocalDate
set REL_DATE = CONVERT(datetime, LEFT(TERR_REL_DATE,10), 104)
Luckily my Global date was already in datetime so I then simply joined the two tables and ran my comparison against the new updated time

SQL Server 2008 UTC Conversion to EST

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])

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

SQL Issue querying database between two dates

I have the following records in the DB below is the created date for each record.
2013-11-09 12:55:43.000
2013-10-29 19:01:53.000
2013-10-29 04:59:42.000
My SQL query looks like this
Select d.Name as DealerName, Sum(c.CommissionAmount) as CommissionAmount
from Dealer d
Left join Commission c on c.Dealerid = d.DealerId
where c.CreatedDate between isnull(#FromDate, c.CreatedDate) and isnull(#ToDate, c.CreatedDate)
Group by d.Name
Order by CommissionAmount desc
When I enter the following dates in to my search functionality
From date = 29/10/2013
To date = 09/11/2013
It only returns one record, when it should return three, yet if I leave From date as it is and pass in null for To date I get two records back
Can someone tell me what I'm doing wrong here?
Thanks
Try this:
When You are using Dates in where clause Always use Same casting on both sides
Select d.Name as DealerName, Sum(c.CommissionAmount) as CommissionAmount
from Dealer d
Left join Commission c on c.Dealerid = d.DealerId
where CAST(c.CreatedDate as DATE) between
CAST(isnull(#FromDate, c.CreatedDate) as DATE) and
CAST(isnull(#ToDate, c.CreatedDate) as DATE)
Group by d.Name
Order by CommissionAmount desc
You can do this by using tow ways one is
1. CAST
CAST(c.CreatedDate as DATE)
2. CONVERT
CONVERT(varchar(10), c.CreatedDate)
Here is the both the ways that you can achieve.
1. where
CONVERT(varchar(10), c.CreatedDate)
between
isnull(#FromDate, c.CreatedDate)
and
isnull(#ToDate, c.CreatedDate)
2. where
CAST(c.CreatedDate as DATE)
between
isnull(#FromDate, c.CreatedDate)
and
isnull(#ToDate, c.CreatedDate)
Difference between cast & convert is You can Apply any style format you need in the CONVERT function .There are many date time format availabe for CONVErT function Refer this link You will get all the styple format in the SQL.
Syntax for the COnvert is
CONVERT ( data_type [ ( length ) ] , expression [ , style ] )
where expression [ , style ] is optional field.
CAST :
Cast is available after the version of SQL 2005. cast also Converts an expression of one data type to another in SQL Server.
Syntax
CAST ( expression AS data_type [ ( length ) ] )
[ ( length ) ] is optional field in Cast
Try This
SELECT d.Name as DealerName, Sum(c.CommissionAmount) as CommissionAmount
FROM Dealer d
LEFT JOIN Commission c on c.Dealerid = d.DealerId
WHERE CONVERT(VARCHAR(10),CAST(c.CreatedDate AS DATE),103)
BETWEEN isnull(#FromDate, c.CreatedDate) and isnull(#ToDate, c.CreatedDate)
Group by d.Name
Order by CommissionAmount desc
The problem is u have defined the variables without time So the #todate will be like '2013-11-09 00:00:00.000'.
But in the table date has time. Between operator will not consider this date '2013-11-09 12:55:43.000' since it is higher than the todate u have mentioned thats y you are getting two rows.
so try this.
CREATE TABLE #temp
(dates DATETIME)
INSERT INTO #temp
VALUES ('2013-11-09 12:55:43.000'),
('2013-10-29 19:01:53.000'),
('2013-10-29 04:59:42.000')
DECLARE #from VARCHAR(50)='29/10/2013',
#to VARCHAR(50) ='09/11/2013'
SELECT *
FROM #temp
WHERE (#from is not null and #to is not null and Cast(dates AS DATE) BETWEEN CONVERT(DATE, #from, 103) AND CONVERT(DATE, #to, 103) ) or 1=1
SQL FIDDLE DEMO