Count with last 4 digits which represent Date - sql

I have a question
Can we convert date 20-06-2011 (dd-mm-yyyy) into 0611 using sql (SQL server database) ?
And
Can we count ID below
keeping in mind last 4 digits which represent date (last 4 digits represent date in the form MMYY) so numbers with last 4 digits 0611 count should be 3
What would be the SQl Query for the count?
ID
AOB2340511
AOB4560511
AOB3500611
AOB4410611
AOB5120611
AOB1250411

EDIT: Corrected DATE data type option.
If your date fields are DATE data types you can do the following.
SELECT RIGHT('0' + CAST(DATEPART(MM, #TheDate) as VARCHAR), 2)
+ RIGHT(CAST(DATEPART(YY, #TheDate) as VARCHAR), 2)
If your date fields are stored as a string type, such as VARCHAR, NVARCHAR, etc, then try the following
select SUBSTRING(TheDate, 4, 2) + SUBSTRING(TheDate, 9, 2)
For the question about count, you can try this
SELECT RIGHT(ID, 4) AS TheDate, Count(*) AS TheCount
FROM MyTable
GROUP BY RIGHT(ID, 4)
If you need a query for the count that also shows the ID value, give this a try
SELECT ID, RIGHT(ID, 4) as MMYY,
COUNT(*) OVER (PARTITION BY RIGHT(ID, 4)) AS TheGroupCount
FROM MyTable
ORDER BY ID

This gives you "YYMM":
SELECT SUBSTRING(CONVERT(VARCHAR,getdate(),12),1,4)
To get the 2-digit month before the 2-digit year you need to do:
SELECT SUBSTRING(CONVERT(VARCHAR,getdate(),12),3,2) + SUBSTRING(CONVERT(VARCHAR,getdate(),12),1,2)
getdate() is just the current datestamp; substitute that with the date field you want to reformat.
CONVERT(...,12) gives you YYMMDD datestamp. See this helpful page for more magic numbers to use as the 3rd parameter: http://sql.dzone.com/news/custom-date-formatting-sql-ser
(BTW, using DATEPART(MM,getdate()) gives a 1-digit month not 2 digits, and DATEPART(YY,getdate()) gives a 4-digit year, not 2 digits. I.e. the DATEPART approach seems doomed)

Related

How to i get Month & Year from SQL in Varchar Type

I Already Created Table (commercials) Column (MyDate) "Varchar(255)"
I Have some manual entries like:
dd-mm-yyyy
01-05-2019
02-05-2019
15-06-2019
16-06-2019
Now i want to select Only One Month and year. like
05-2019 or 06-2019
Please tell me how i can select only Month and year from this column.
You don't need any conversion among data types, since you want to extract a string from string, and to extract the part with mm-yyyy format pattern, just use substring() function as below :
select distinct substring(replace(MyDate,' ',''), 4, 7) as "Month-Year"
from myTable;
Month-Year
----------
05-2019
06-2019
By the way, consider using replace(MyDate,' ','') (trim(MyDate) for version 2017+) against the probabilty of having space within the strings.
Use string operations:
select right(col, 4) as yyyy,
right(col, 7) as mmyyyy,
substring(col, 4, 2) as mm
Using DISTINCT on Only MM-YYYY part of your data will return a MM-YYYY combination only once as per your requirement. Sample script is shown below-
SELECT DISTINCT RIGHT(MyDate, 7)
FROM commercials

Get only month and year in SQL Server

I want to fetch only month and year from a date column in SQL Server.
Example: if today's date is 02/03/2019, then I want 0319.
Note: I want the result in same order (2 digit month and 2 digit year). Zero should not be removed from month.
As an alternative approach, you could go for:
RIGHT(REPLACE(CONVERT(varchar(8),DateColumn,3),'/',''),4)
You can create a number using:
select month(datecol) * 100 + (year(datecol) % 100)
Prepending the zeros requires a bit more work:
select right('0' + convert(varchar(255), month(datecol) * 100 + (year(datecol) % 100)), 4)
Or, you can use format():
select format(datecol, 'MMyy')
You can try this
substring(convert(nvarchar,#date,12),3,2) + left(convert(nvarchar,#date,12),2)
You can create an user defined function, and then apply to your column/s
create function udf_Getmonthyear(#date as date)
RETURNS nchar(4)
BEGIN
DECLARE #d_format nchar(6) = (select convert(nvarchar,#date,12))
RETURN (select SUBSTRING(#d_format,3,2) + left(#d_format,2))
end
go
Use function DATEPART in TSQL to get any part of a DateTime value. e.g:
DATEPART(yy,datecol) gives you 4 digit year part of a DateTime column (e.g: datecol), using the % (modulus) operator you can get 2 digit year DATEPART(yy,datecol)%100.
DATEPART(mm,datecol) gives you month part of the datecol field.
select Right('0'+cast(DATEPART(mm,datecol) as varchar(2)),2) +
Right('0'+cast(DATEPART(yy,datecol)%100 as varchar(2)),2) MonthYearPart
from MyTable
Regards

Find Birthday in upcoming month

I Need help in finding upcoming birthday in a month.
My Data is something like below , Both data types are nvarchar
Could anyone help me with the sql query please? how to set the DOB column into a date format and then find the birthday with month as 11 and date as 24.
Thanks in advance
Assuming SQL Server, you can use month() to extract the month from a date, for example getdate(), which is the current point in time. With left() you can extract the first characters of a string. That leads to something like:
SELECT [Name],
[Dob(mmdd)]
FROM elbat
WHERE month(getdate()) = left([Dob(mmdd)], 2);
In Microsoft SQL Server you can Create a date using the DATEFROMPARTS(int year, int month, int day) function. To get your month and day you would have to get the 2 parts of the string, the first 2 characters for month and the third and fourth characters as the day, you can use the SUBSTRING function for this. Then take each pair of characters for month and day and cast to int and use them in the DATEFROMPARTS function.
Then you want to see if your newly created date is BETWEEN today AND one month from today. So you could do something like this:
SELECT *
FROM SomeTable
WHERE
DATEFROMPARTS(YEAR(GETDATE()), CAST(SUBSTRING([Dob(mmdd)], 1, 2) as INT), CAST(SUBSTRING([Dob(mmdd)], 3, 2) as INT))
BETWEEN
DATEADD(DAY, -1, GETDATE()) AND DATEADD(MONTH, 1, GETDATE())
Note: this assumes [Dob(mmdd)] is always 4 characters.
You don't need the DOB in a date format. I am unclear what "upcoming" month means, but I suspect that it means a calendar month. If the current month, then:
where month(getdate()) = cast(left(dob, 2) as int)
If the next month, then:
where month(dateadd(month, 1, getdate())) = cast(left(dob, 2) as int)
Thanks, Everyone for the help.. I got this working,. both works perfect
select [USER_ID],[EMP_FULL_NM],[Birthday_Date] from [dbo].[COE]
where month(getdate())=left([Birthday_Date],2)
select [USER_ID],[JOINING_DT],[EMP_FULL_NM] from [dbo].[COE]
where SUBSTRING(CONVERT(VARCHAR(10), [JOINING_DT], 101),1,2) = month(getdate())

query to search dates which are stored as string in the database

I have a table where I store an activity completion date as varchar. The format of the date stored is MM/DD/YYYY HH:MM:SS.
I have search window where I have two fields Completion date from and completion date to.The date format selected here is MM/DD/YYYY.
How do I write a query such that I am able to fetch the activity completion between two given dates from the table which has the dates stores as varchar.This table was created a long time back and no thought was given to saving dates as datetime.
You can use SQL CONVERT to change your columns to DATE format but that will cause performance issues.
SELECT *
FROM MyTable
WHERE CONVERT(DATETIME, MyDate) >= CONVERT(DATE, '01/01/2014')
AND CONVERT(DATETIME, MyDate) <= CONVERT(DATE, '01/31/2014')
CONVERT documentation - http://msdn.microsoft.com/en-us/library/ms187928.aspx
if you are unable to change how data is stored, than for better performance , you can create view with calculated column that converts VARCHAR to DATETIME. After that can create index on calculated column. Index on Computed Column documentation
Use the SUBSTRING function to get the date parts in a comparable order (i.e. yyyymmdd):
select *
from mytable
where
CONCAT( SUBSTRING(thedate, 7, 4) , SUBSTRING(thedate, 4, 2) , SUBSTRING(thedate, 1, 2) )
between
CONCAT( SUBSTRING(#FROMDATE, 7, 4) , SUBSTRING(#FROMDATE, 4, 2) , SUBSTRING(#FROMDATE, 1, 2) )
and
CONCAT( SUBSTRING(#TODATE, 7, 4) , SUBSTRING(#TODATE, 4, 2) , SUBSTRING(#TODATE, 1, 2) )
;
You could use this code :
select * from table_name
where CAST(col1 as date )
between CAST(Completion date from as date )
and CAST(Completion date to as date);
Function syntax CAST:
CAST ( expression AS data_type )
You can use below if the date format is {yyyy-MM-dd}, or you can adjust the charindex's index value depending on format
SELECT *
FROM table
WHERE
CHARINDEX('-', col_value, 0) = 5
AND CHARINDEX('-', col_value, 6) = 8
AND LEN(col_value) = 10
The above piece will look for first occurrence of char '-' at position 5 and the second char '-' at position 8 while the entire date value's length is equal to 10 chars
This is not full proof, but will narrow down the search. If you want to add time then just expand the criteria in the where to accommodate the format i.e. {yyyy-MM-dd 00:00:00.000}
This is a safe way to query the data, without any unexpected 'invalid cast / convert' errors.

Date arithmetic in SQL on DB2/ODBC

I'm building a query against a DB2 database, connecting through the IBM Client Access ODBC driver. I want to pull fields that are less than 6 days old, based on the field 'a.ofbkddt'... the problem is that this field is not a date field, but rather a DECIMAL field, formatted as YYYYMMDD.
I was able to break down the decimal field by wrapping it in a call to char(), then using substr() to pull the year, month and day fields. I then formatted this as a date, and called the days() function, which gives a number that I can perform arithmetic on.
Here's an example of the query:
select
days( current date) -
days( substr(char(a.ofbkddt),1,4) concat '-' -- YYYY-
concat substr(char(a.ofbkddt),5,2) concat '-' -- MM-
concat substr(char(a.ofbkddt),7,2) ) as difference, -- DD
a.ofbkddt as mydate
from QS36F.ASDF a
This yields the following:
difference mydate
2402 20050402
2025 20060306
...
4 20110917
3 20110918
2 20110919
1 20110920
This is what I expect to see... however when I use the same logic in the where clause of my query:
select
days( current date) -
days( substr(char(a.ofbkddt),1,4) concat '-' -- YYYY-
concat substr(char(a.ofbkddt),5,2) concat '-' -- MM-
concat substr(char(a.ofbkddt),7,2) ) as difference, -- DD
a.ofbkddt as mydate
from QS36F.ASDF a
where
(
days( current date) -
days( substr(char(a.ofbkddt),1,4) concat '-' -- YYYY-
concat substr(char(a.ofbkddt),5,2) concat '-' -- MM
concat substr(char(a.ofbkddt),7,2) ) -- DD
) < 6
I don't get any results back from my query, even though it's clear that I am getting date differences of as little as 1 day (obviously less than the 6 days that I'm requesting in the where clause).
My first thought was that the return type of days() might not be an integer, causing the comparison to fail... according to the documentation for days() found at http://publib.boulder.ibm.com/iseries/v5r2/ic2924/index.htm?info/db2/rbafzmst02.htm, it returns a bigint. I cast the difference to integer, just to be safe, but this had no effect.
You're going about this backwards. Rather than using a function on every single value in the table (so you can compare it to the date), you should pre-compute the difference in the date. It's costing you resources to run the function on every row - you'd save a lot if you could just do it against CURRENT_DATE (it'd maybe save you even more if you could do it in your application code, but I realize this might not be possible). Your dates are in a sortable format, after all.
The query looks like so:
SELECT ofbkddt as myDate
FROM QS36F.ASDF
WHERE myDate > ((int(substr(char(current_date - 6 days, ISO), 1, 4)) * 10000) +
(int(substr(char(current_date - 6 days, ISO), 6, 2)) * 100) +
(int(substr(char(current_date - 6 days, ISO), 9, 2))))
Which, when run against your sample datatable, yields the following:
myDate
=============
20110917
20110918
20110919
20110920
You might also want to look into creating a calendar table, and add these dates as one of the columns.
What if you try a common table expression?
WITH A AS
(
select
days( current date) -
days( substr(char(a.ofbkddt),1,4) concat '-' -- YYYY-
concat substr(char(a.ofbkddt),5,2) concat '-' -- MM-
concat substr(char(a.ofbkddt),7,2) ) as difference, -- DD
a.ofbkddt as mydate
from QS36F.ASDF a
)
SELECT
*
FROM
a
WHERE
difference < 6
Does your data have some nulls in a.ofbkddt? Maybe this is causing some funny behaviour in how db2 is evaluating the less than operation.