sorting date in sql - sql

I have dates stored in my column as
Wednesday, November 21, 2018
Wednesday, August 22, 2018
Wednesday, August 22, 2018
Wednesday, August 22, 2018
Wednesday, August 15, 2018
Tuesday, November 27, 2018
Tuesday, November 06, 2018
Monday, November 19, 2018
I am using
ORDER BY CONVERT(varchar(100), submissionDate, 101) DESC
but its not giving me column in sorted way. My column is NVARCHAR(MAX)

If you are stuck with the column type nvarchar, you can convert the value to a date with something like this:
SELECT *, submissionDate
, convert(date
, right(submissionDate, len(submissionDate)
- charindex(',', submissionDate))
, 107) as my_date
FROM your_table
ORDER BY my_date
Or just
SELECT submissionDate
FROM your_table
ORDER BY convert(date
, right(submissionDate, len(submissionDate)
- charindex(',', submissionDate))
, 107)
The conversion is a bit cumbersome because of your date format. Sql Server does not seem to have a matching built-in format. So we get rid of the day of the week (Monday,..) by removing the part before the first comma and then the result complies with format 107 (Mon dd, yyyy).

SQL Server is pretty good about recognizing arcane formats as dates, but not good enough for this situation. I think that stuff() makes this simpler:
select convert(date,
stuff(datestr, 1, charindex(',', datestr) + 1, '')
)
from (values ('Wednesday, November 21, 2018')) v(datestr)

Related

String date format convert to date

I need to convert this string to yyyy-MM-dd date format:
December 31, 2014 to 2014-12-31
May 31 , 2018 to 2018-05-31
Any suggestion?
Regards!
You can just use convert():
select convert(date, 'December 31, 2014')
SQL Server is pretty good about doing such conversions.
So this works in both cases:
select convert(date, datestr)
from (values ('December 31, 2014'), ('May 31 , 2018')) v(datestr);
You can also use as shown Here
Select cast('December 31, 2014' as date) as [Date]
Select cast('December 31, 2014' as date) as [Date]
or in higher version of SQL Server provide format string value for different date format as you want.
SELECT FORMAT(cast('December 31, 2014' as Date),'yyyy-MM-dd','en-US') AS[DATE IN US FORMAT]

More date format conversion SQL

Hi I am working with SQL 2014 and I need to convert the following 2 date formats:
12/31/18 - Varchar
12/31/2018 - Varchar
to this format final format
December 31,2018 Varchar
I know that use varchar is not the correct.
any suggestion?
Try to use:
DECLARE #f varchar(50) = '12/31/18'
SELECT FORMAT(CAST(#f AS DATETIME), N'MMMM dd, yyyy')
OUTPUT:
December 31, 2018
And your second variant:
DECLARE #f varchar(50) = '12/31/2018'
SELECT FORMAT(CAST(#f AS DATETIME), N'MMMM dd, yyyy')
OUTPUT:
December 31, 2018
You can try the following query also using
create table DateValue (DateVal varchar(10))
insert into DateValue values
('12/31/18'),
('12/31/2018'),
('01/31/18'),
('01/31/2018')
Select
DateName( month , DateAdd( month , DATEPART(MONTH, DateVal) , 0 ) - 1 ) + ' ' +
Cast(DATEPART(dd, DateVal) as Varchar) + ', ' +
+ Cast (DATEPART(YYYY, DateVal) as Varchar) as VarcharDate
from DateValue
The output will be as shown below.
VarcharDate
----------------
December 31, 2018
December 31, 2018
January 31, 2018
January 31, 2018
This query will also run in lower version of SQL Server where format() is not available.
Live Demo

Show Date as dddd Mmmm d, yyyy SQL

Trying to show the date as Thursday, August 2, 2018 format. Its stored as 20180802 in the table. The column type is set to char. Any help is appreciated.
I'm using SQL Server 2014.
Thanks
Use the following with DateName and convert functions :
select DateName( month , q.dt )+' '+convert(char,day(q.dt))+', '+convert(char,year(q.dt))
from
(
select convert(date,'20180802') as dt
) q;
SQL Fiddle Demo
With respect to your last comment make your query as :
select DateName( weekday , q.dt )+' '+
DateName( month , q.dt )+' '+
convert(char,day(q.dt))+', '+convert(char,year(q.dt)) as "Date"
from
(
select convert(date,'20180802') as dt
) q;
Date
------------------------
Thursday, August 2, 2018
Adding to Barbaros Özhan response,
SELECT DateName(dw,q.dt) +', '+DateName(month, q.dt)+' '+CONVERT(VARCHAR, DAY(q.dt))+', '+CONVERT(VARCHAR, YEAR(q.dt))
FROM
(
SELECT CONVERT(DATE, '20180802') AS dt
) q;
Since you are 2014, you can use format().
Format() has some great functionality, but it is not known to be a performer.
Also, since your "date" is stored as a string, I would suggest try_convert() or try_cast() to allow for any unexpected data.
Example
Select format(try_convert(date,'20180802'),'dddd, MMMM d, yyyy')
Returns
Thursday, August 2, 2018

Updating table based on global substring match via IF statement or CASE

I have hundreds of thousands of rows with four date columns that were imported as such:
Mon Nov 14 14:52:46 PST 2011
Fri Nov 04 07:50:21 PDT 2011
Thu Dec 01 00:00:00 PST 2011
There are three months: Nov, Dec, Jan. I want my new date format saved to new columns in this format:
11-14-2011, 11-04-2011, 12-01-2011 and so on....
I'm able to do this via an update statement that matches the substring month name and replaces it with the matching numeric. So I can do it with something like this:
UPDATE tabel
set col1 = REPLACE(substring(col2, 5,3) 'Nov', 11)
And it works for the first month I run. But when I then add Dec and Jan, then it only works for those months and resets the string for the three letter months in all the other rows I just did.
I don't know how to execute this UPDATE and REPLACE command in the right way so it matches all three months in the database and then writes out the new format to the new column like I want. I'm a bit new to T-SQL and so far I'm overwhelmed with the amount of documentation out there. I've tried putting all three months into a series of UPDATE statements and that did not work. I think it needs to go row by row, test a condition and then execute the update if it matches.
Maybe like this:
IF #dateColSubString = 'Jan' Then
UPDATE table
set newDateCol = REPLACE(substring(col2, 5,3) 'Jan', 01) + '-2012'
COMMIT
IF #dateColSubString = 'Dec' Then
UPDATE table
set newDateCol = REPLACE(substring(col2, 5,3) 'Dec', 12) + '-2011'
COMMIT
to make values like this in the new column '01-2011' and then have those not be reset to there old values when I run the same update request for 'Nov' and then 'Dec' to change those strings.
I hope this makes sense.
Try this and do whatever you want with your datetime
DECLARE #t TABLE(str varchar(100))
INSERT #t
VALUES('Mon Nov 14 14:52:46 PST 2011'),('Fri Nov 04 07:50:21 PDT 2011'),('Thu Dec 01 00:00:00 PST 2011')
SELECT
CAST(DATEPART(MONTH, CAST(SUBSTRING(str, 5, 6) +' '+RIGHT(str, 4) AS DATETIME)) AS VARCHAR) +'-'+ RIGHT(str, 4),
CAST(SUBSTRING(str, 5, 6) +' '+RIGHT(str, 4) AS DATETIME),
CONVERT(VARCHAR, CAST(SUBSTRING(str, 5, 6) +' '+RIGHT(str, 4) AS DATETIME), 110)
FROM #t
In your case, a suppose, it is like this - you only have to choose which result is more suitable for you and adopt the corresponding query row:
SELECT
CAST(DATEPART(MONTH, CAST(SUBSTRING(order_send, 5, 6) +' '+RIGHT(order_send, 4) AS DATETIME)) AS VARCHAR) +'-'+ RIGHT(order_send, 4),
CAST(SUBSTRING(order_send, 5, 6) +' '+RIGHT(order_send, 4) AS DATETIME),
CONVERT(VARCHAR, CAST(SUBSTRING(order_send, 5, 6) +' '+RIGHT(order_send, 4) AS DATETIME), 110)
FROM YourTableName
If you are fine with losing the timezone information, you could simply remove the day of week and time zone parts and convert the resulting string to datetime using simple CAST or CONVERT, like this:
;
WITH StringDates (OldDateCol) AS (
SELECT 'Mon Nov 14 14:52:46 PST 2011' UNION ALL
SELECT 'Fri Nov 04 07:50:21 PDT 2011' UNION ALL
SELECT 'Thu Dec 01 00:00:00 PST 2011'
)
SELECT
OldDateCol,
NewDateCol = CAST(SUBSTRING(STUFF(OldDateCol, 21, 4, ''), 5, 99) AS datetime)
FROM StringDates
that is, STUFF removes the time zone part and SUBSTRING omits the day of week.
Here's the result set:
OldDateCol NewDateCol
---------------------------- -----------------------
Mon Nov 14 14:52:46 PST 2011 2011-11-14 14:52:46.000
Fri Nov 04 07:50:21 PDT 2011 2011-11-04 07:50:21.000
Thu Dec 01 00:00:00 PST 2011 2011-12-01 00:00:00.000
On the other hand, if you are (or might eventually be) using a datetimeoffset column for storing the converted values and are interested in preserving the time zone bit of information, you could try the following method:
;
WITH StringDates (OldDateCol) AS (
SELECT 'Mon Nov 14 14:52:46 PST 2011' UNION ALL
SELECT 'Fri Nov 04 07:50:21 PDT 2011' UNION ALL
SELECT 'Thu Dec 01 00:00:00 PST 2011'
),
DatesAndTimeZones AS (
SELECT
OldDateCol,
NewDateCol = CAST(SUBSTRING(STUFF(OldDateCol, 21, 4, ''), 5, 99) AS datetime),
TimeZoneName = SUBSTRING(OldDateCol, 21, 4)
FROM StringDates
),
TimeZones (Name, Offset) AS (
SELECT 'PST', '-08:00' UNION ALL
SELECT 'PDT', '-07:00'
)
SELECT
d.OldDateCol,
NewDateTimeOffsetCol = TODATETIMEOFFSET(d.NewDateCol, t.Offset)
FROM DatesAndTimeZones d
INNER JOIN TimeZones t ON d.TimeZoneName = t.Name
Here the conversion is done in two steps.
The first step converts the strings to datetime values, same as before, and also extracts the time zone names from them.
Basically, those two values would be enough to convert datetime to datetimeoffset, but SQL Server doesn't recognise time zone names, it can only understand offsets, in the form of either +hh:mm or -hh:mm. So you need to replace the names with the corresponding offsets, which can be done with the help of a reference table (the TimeZones CTE above plays its part).
So the next (and last) step is joining to the reference table and calling the TODATETIMEOFFSET() function to get the final results.
Here's the results of the second query:
OldDateCol NewDateTimeOffsetCol
---------------------------- ----------------------------------
Mon Nov 14 14:52:46 PST 2011 2011-11-14 14:52:46.000 -08:00
Fri Nov 04 07:50:21 PDT 2011 2011-11-04 07:50:21.000 -07:00
Thu Dec 01 00:00:00 PST 2011 2011-12-01 00:00:00.000 -08:00
References:
datetimeoffset (Transact-SQL)
TODATETIMEOFFSET (Transact-SQL)
Date and Time Functions (Transact-SQL)

Datetime selection query group by day

I've got a question for my SQL query I've got too write. It's a long time ago since I've written an query so I could use some help with mine. I've tried looking for examples but didn't find the right result. Ive written an query but its really isn't working for me..
What im trying to do is get the sum of the total power consumption for each date in my database.
My table looks like:
|HistoryProbes|
|-------------|
|id (int) pk |
|timestamp (datetime) formatted as: "yyyy-MM-ddTHH:mm:ss"|
|PowerConsumption (int)|
I've found a sample that did quite work.. But it isnt the best solution for me..
it can be found at : http://cephas.net/blog/2005/12/06/sql-server-group-by-datetime/
So far i got this working
SELECT distinct CONVERT(varchar, timestamp, 111) AS thedate
FROM HistoryProbes
I got values 25/11/2009 and 24/11/2009 but i cant manage to get the sum of the PowerConsumption
Thanks.
Something like this will give you the sum per day
DECLARE #HistoryProbes TABLE(
id INT,
timesmp DATETIME,
PowerConsumption INT
)
INSERT INTO #HistoryProbes (id,timesmp,PowerConsumption) SELECT 1, '01 Jan 2009 12:00:00',1
INSERT INTO #HistoryProbes (id,timesmp,PowerConsumption) SELECT 2, '01 Jan 2009 11:00:00',2
INSERT INTO #HistoryProbes (id,timesmp,PowerConsumption) SELECT 3, '01 Jan 2009 13:00:00',3
INSERT INTO #HistoryProbes (id,timesmp,PowerConsumption) SELECT 4, '01 Jan 2009 14:00:00',4
INSERT INTO #HistoryProbes (id,timesmp,PowerConsumption) SELECT 5, '02 Jan 2009 12:00:00',14
INSERT INTO #HistoryProbes (id,timesmp,PowerConsumption) SELECT 6, '02 Jan 2009 11:00:00',24
INSERT INTO #HistoryProbes (id,timesmp,PowerConsumption) SELECT 7, '03 Jan 2009 13:00:00',34
INSERT INTO #HistoryProbes (id,timesmp,PowerConsumption) SELECT 8, '03 Jan 2009 14:00:00',44
SELECT DATEADD(dd,0, DATEDIFF(dd,0,timesmp)),
SUM(PowerConsumption)
FROM #HistoryProbes
GROUP BY DATEADD(dd,0, DATEDIFF(dd,0,timesmp))
select CONVERT(varchar, timestamp, 111) as timestamp_by_day
, sum(PowerConsumption) as total_power
from HistoryProbes
group by CONVERT(varchar, timestamp, 111)
order by CONVERT(varchar, timestamp, 111)
Try this:
SELECT Convert(varchar, timestamp, 111) as thedate, SUM(PowerConsumption) as Total
FROM HistoryProbes
GROUP BY Convert(varchar, timestamp, 111)
I'm not sure why you need distinct in there; since you're not joining to any other tables