i have dates stored as chars in db (i know, but its not my db nor my idea..).
One of the dates is stored as MMYYYY (012016,022016...) and the second one is stored as YYYYMMDD (20160101,20160202...).
Is there a way to compare those dates? I need to take one date and select all of the second dates which are at least one year older then the first one...
Thank you for any help !
So for example i have Date1 field with values : 012014,012015,012016
and Date2 field with value: 20141005
And i need only Date1 which is at least one year older then Date2 so in this case it will return only 012016
I make two ctes to show how to work it out. I assume MMYYYY are stored as nvarchar or varchar and YYYYMMDD are the same type. If not - you will need one/few conversions on YYYYMMDD field.
;WITH cte AS (
SELECT '012016' as MMYYYY
UNION ALL
SELECT '022016'
), cte2 AS (
SELECT '20160101' AS YYYYMMDD
UNION ALL
SELECT '20160202'
)
SELECT *
FROM cte c
INNER JOIN cte2 c2
ON YYYYMMDD LIKE RIGHT(MMYYYY,4)+LEFT(MMYYYY,2) +'%'
Output:
MMYYYY YYYYMMDD
012016 20160101
022016 20160202
EDIT:
To find out differences in years use this:
DATEDIFF(year,CAST(YYYYMMDD as date), CAST(RIGHT(MMYYYY,4)+LEFT(MMYYYY,2)+'01' as date))
You can convert both fields into type DATE, then compare them.
For MMYYYY, you can use the function DATEFROMPARTS() to build a date. For example, convert 012014 into date:
-- DATEFROMPARTS(year, month, day)
DATEFROMPARTS(RIGHT('012014', 4), LEFT('012014', 2), 1)
For YYYYMMDD, it is easier, because this is the format ISO with Time Style 112. You can use the CONVERT() function to do the conversion :
CONVERT(DATE, '20141005', 112)
And here's how the final query looks like :
WITH casted AS (
SELECT
DATEFROMPARTS(RIGHT(date1, 4), LEFT(date1, 2), 1) AS d1,
CONVERT(DATE, date2, 112) AS d2,
-- ...
FROM yourTable
)
SELECT *
FROM casted
WHERE d1 <= DATEADD(YEAR, -1, d2)
try this
column1 is stored MMYYYY format and column2 is stored YYYYMMDD.
where column1= case when datepart(month,taskDuedate)>9 then convert(varchar,datepart(month,taskDuedate))else '0'+convert(varchar,datepart(month,taskDuedate))end+convert(varchar,datepart(year,taskDueDate))
Related
I'm trying to perform a query in SQL Server. I'm having trouble filtering the date. The output is always the same, the data doesn't get filter by date.
The date comes in the following format:
29-12-2020 16:38
31-12-2020 17:43
I tried to filter doing all the following but none worked out:
select
start_date
from table_1
where start_date between '01-01-2021 00:00:00' and '31-01-2021 00:00:00'
select
start_date
from table_1
where start_date between '01-01-2021 00:00' and '31-01-2021 00:00'
select
start_date
from table_1
where start_date between '01-01-2021' and '31-01-2021'
I also tried to cast it but I didn't have luck:
select
cast(start_date as date) as start_date
from table_1
where start_date between '2021-01-01' and '2021-01-31'
Can anyone help me?
Regards
You have a string. I strongly suggest making it a date/time of some sort. The following conversion works:
select convert(datetime, left(str, 10), 105) + convert(datetime, right(str, 5))
from (values ('29-12-2020 16:38')) v(str);
One operation is a computed column:
alter table table_1 start_date_dt as
( convert(datetime, left(start_date, 10), 105) + convert(datetime, right(start_date, 5)) )
Then you can use this value for your where clause. Or better yet. Fix the data! Don't store values in strings when there is an appropriate data type.
I have a query (SQL Server 2012) that combines UNIX timestamps from two different tables into one column, which on its own works fine. The query needs to be sorted (descending) by the combined date column AND converted into a readable format.
If I attempt to sort after the date has been converted, it doesn't work as it is now a VARCHAR and returns:
05/02/2018
06/01/2017
07/03/2016
First I tried including a date conversion in the ORDER BY clause but that clearly doesn't work.
I then thought I could use a subquery to perform the sort then do the conversion in the main query (see below for what I currently have), but this is returning the error:
Invalid usage of the option NEXT in the FETCH statement.
I'm not using a fetch statement, so I'm wondering if there's something in my nesting that SQL Server doesn't like.
Any clues would be terrific.
-- Convert Epoch timestamp format to readable (and unsortable) dd/MM/yyyy format
SELECT CONVERT(VARCHAR(10), DATEADD(second, OuterTable.thedate-DATEDIFF(second, GETDATE(), GETUTCDATE()), CONVERT(DATETIME, '1970-01-01', 103)), 103) AS FinalDate
FROM (
-- Subquery only exists to do a proper date sort
SELECT thedate
FROM
(
SELECT
-- Determine which date to use
CASE WHEN x.dateX IS NOT NULL
THEN x.dateX
ELSE y.dateY
END AS thedate
-- Get date from first table
FROM (
SELECT id, dateX -- date is in Epoch format (BIGINT)
FROM tableX
) AS x
-- Get date from second table
JOIN (
SELECT id, dateY -- date is in Epoch format (BIGINT)
FROM tableY
) AS y
ON x.id = y.id
)
-- Perform sort while date is still in epoch format
ORDER BY thedate DESC
) AS OuterTable
IMO this should work for you:
SELECT CONVERT(VARCHAR(10), DATEADD(second, COALESCE(x.dateX, y.dateY) - DATEDIFF(second, GETDATE(), GETUTCDATE()), CONVERT(DATETIME, '1970-01-01', 103)), 103) AS FinalDate
FROM tableX AS x
INNER JOIN tableY AS y
ON x.id = y.id
ORDER BY COALESCE(x.dateX, y.dateY) DESC;
Not sure when copy/paste the CONVERT function. Is it so complicated to convert epoch to dd/MM/yyyy in MSSQL?
I have a column that stores a date as char in the format 'YYYYMMDD'. Now I want to convert it to a real date.
I tried
select cast (DATEFIELD as DATE) as MyDate
But it only returns the old YYYYMMDD format labeled as 'DATE'. What am I doing wrong?
SELECT TIMESTAMP_FORMAT("DATEFIELD",'YYYYMMDD') as "MyDate"
Use the CONVERT function and the style 112 to get the output in YYYYMMDD
SELECT CONVERT(DATEFIELD, 112) as MyDate
FROM yourtable
Or style 100 for mon dd yyyy hh:mi
SELECT CONVERT(DATEFIELD, 100) as MyDate
FROM yourtable
Simply convert it.
SELECT TIMESTAMP_FORMAT("DATEFIELD",'YYYYMMDD') as MyDate
FROM <your_table>
I have a stored procedure where want check that a date is between a fixed date and the current date/time (with GETDATE()):
SELECT
a, b
FROM myTbl
WHERE
DATE BETWEEN 'Day start datetime' AND GETDATE()
...for example :
WHERE
DATE BETWEEN '2013-09-10 00:00:00.00' AND 'GETDATE()'
How to do it?
A pair of DATEADD/DATEDIFF calls will round a date down to the previous midnight:
SELECT a , b
FROM myTbl
WHERE DATE BETWEEN DATEADD(day,DATEDIFF(day,0,GETDATE()),0) and GETDATE()
Alternatively, if you're on SQL Server 2008 or later:
SELECT a , b
FROM myTbl
WHERE DATE BETWEEN CONVERT(date,GETDATE()) and GETDATE()
'GETDATE()' is a string literal, GETDATE() is a T-SQL function.
Your query should look like:
SELECT a , b
FROM myTbl
WHERE DATE BETWEEN '2013-09-10 00:00:00.0' and GETDATE()
I think WHERE DATE BETWEEN '2013-09-10 00:00:00.00' and GETDATE() (without the single quotes around the GETDATE() call) should work just fine.
You can get Day start date time by converting Getdate() return value to a Date type and again to Datetime as below.
select a,b
from myTbl
where [date] between convert(datetime,convert([date], getdate()))
and getdate()
I have a question. I have a SQL Server 2008 table with a field column. I have for example the Following dates:
1/1/2001
5/5/2004
8/5/2009
10/7/2011
5/5/2012
1/13/2014
Id like to be able to show all dates >= the current date (7/29/2011) as well as largest table date that is < current date. In this example, the result would be all dates >= 8/5/2009.
Can someone help guide me please??
select max(date) [date] from table where date < getdate()
union
select date from table where date >= getdate()
If I understand correctly, you want to include the date prior to the current date. GETDATE() will get the current date (with time). If you're alright with that, then this should work. Otherwise, you may have to parse out just the date from GETDATE()
SELECT TheDate
FROM DateTable
WHERE TheDate >= (SELECT MAX(TheDate) FROM DateTable WHERE TheDate < GETDATE())
This gets all dates greater than or equal to the most recent date before the current date.
I am not entirely sure I understand, but this looks like a BETWEEN the relevant dates. Or is there something more I am missing?
Assuming your table is called DateTable and your field is called TheDate, do it like this:
SELECT TheDate
FROM DateTable
WHERE TheDate >= DATEADD(d, -2, GETDATE())
Good luck!
It depends on the SQL server you're using. In postgres, for example, you need something like
SELECT fields FROM table WHERE date_field >= CURRENT_DATE - 1
But other SQL servers have different ways to specify "yesterday"
SELECT d1.*
FROM dates d1
LEFT JOIN dates d2 ON d1.Date < d2.Date AND d2.Date < GETDATE()
WHERE d2.Date IS NULL
Explanation:
Select every date for which there does not exist a date that is both earlier than today and later than the one being inspected.
Lots of guessing here based on loose narrative and unknown data types.
DECLARE #t TABLE(d DATE);
INSERT #t SELECT '20010101'
UNION ALL SELECT '20040505'
UNION ALL SELECT '20090805'
UNION ALL SELECT '20111007'
UNION ALL SELECT '20120505'
UNION ALL SELECT '20140113';
DECLARE #now DATE = SYSDATETIME();
WITH t AS
(
SELECT d, rn = ROW_NUMBER() OVER (ORDER BY d)
FROM #t
)
SELECT t.d
FROM t LEFT OUTER JOIN t AS x
ON t.rn = x.rn - 1
WHERE COALESCE(x.d, #now) >= #now
ORDER BY t.d;