Get customers age in months from a given column (SQL Server 2017) - sql-server

I am new to SQL just wanted to know if I have one row with date of birth of few customers and I have to create a new column while creating a view with the customer_id and customer age in month as of today(Age_in_months = Current date - Date of birth of customer). How do I do it ?
I have tried date diff , some suggested to use floor and cast but I keep getting errors
One of them
Msg 245, Level 16, State 1, Line 1
Conversion failed when converting the varchar value '01-05-1974' to data type int.
Can somebody please suggest a very simple solution to this?
Thank you!

Thanks you as I see your query works fine went data is inserted manually . I imported the CSV file so this created a string type entry in sql . Your query gave me the same error I just had to fix it with convert
select customer_Id ,
DOB, DATEDIFF(month, CONVERT(date, Customer.DOB, 103), GETDATE()) as
[Age In Months] from Customer;

Since you haven't provided the Table or Column names I will assume the Table is Customers and the columns are id and dob.
Here is some example SQL to get the information
select
id as [Customer ID],
dob as [Date Of Birth],
datediff(month, cast(dob AS DATE), getdate()) as [Age In Months]
from
customers
First, we will take the Date Of Birth and make sure it is a date and not a Varchar or int, then we wrap that in a DATEDIFF to get the difference between the date in the dob column and the current date in months.
And this is the output
Customer ID Date Of Birth Age In Months
----------- ----------------- -------------
1 01-01-1991 331
2 01-01-2018 7

Related

Snowflake Extracting Month, year from date

I have a table with a column called created_date that has date like 2020-01-01 00:00:00.000
and I'm trying to create a column that will show only the year, another one the month
and one that shows the month as a string
here what I try
select date_part(year,'created_date ') as year,
date_part(month, 'created_date ') as month
to_char(Month, 'created_date') as month_name,
user_name,
product
from user_table
Unfortunately when running the query above, I get an error that Function Extract do not support VARCHAR(10) argument type
The result I'm trying to get is to who a table like
year month month_name user_name product
2021 01 January John Doe Ninja Mixer
2021 05 May Clide Smith Blender
Any help will be appreciated as I'm mostly used to MS sql and we just switch to snowflake.
Assuming the "created_date" is stored as a timestamp or datetime (synonyms), then you just need to remove the single quotes from around the created_date column name and change "to_char" to use the "monthname" function:
select date_part(year, created_date) as year,
date_part(month, created_date) as month,
monthname(created_date) as month_name,
user_name,
product
from user_table

Update Day and Month Except Year From Another Column

I have table with two datetime columns in SQL Server 2000, I want to update only day and month in column_a with day and month in column_b except year.
For example:
column_a
----------
1/2/2009
1/2/2002
1/2/2016
3/1//1998
11/12/1987
column_b
---------
31/12/2015
11/10/2005
27/6/2017
31/12/2010
31/12/2011
Desired results:
31/12/2009
11/10/2002
27/6/2016
31/12/1998
31/12/1987
Thank you for your help.
Using date literals should work in SQL Server 2000, style 112 returns the date in YYYYMMDD so take the YYYY of one and add to MMDD of the other and convert that to datetime.
update tablex
set columnb = convert(datetime(left(convert(varchar, column_a, 112), 4) +
right(convert(varchar, column_b, 112), 4), 112)
It's a great deal easier in later versions. SQL Server 2000 is dead to me.
Use DATEFROMPARTS ( year, month, day )
update tablex
set columnb = datefromparts(year(column_a),month(column_b), day(column_b))

SQL Server: Find the number of substring occurrences of converted data

I have a huge amount of data and I want to count the number of occurrence for a certain column. What makes this confusing is that it is not just finding the same value of the column, but only part of it.
My table contains TimeStamp in format of (YYYY-MM-DD HH:MM:SS), and I want to apply this SQL command only to YYYY-MM-DD part and count the number of occurrence of each based on that. For example, if my data are as follows:
ID|TimeStamp
--+--------------------
00|2017-08-31 09:00:00
01|2017-08-31 11:00:00
02|2017-08-31 16:30:00
03|2017-08-31 22:00:00
04|2017-09-01 09:00:00
05|2017-09-01 23:40:00
06|2017-09-02 10:30:00
07|2017-09-02 13:00:00
08|2017-09-02 23:00:00
then I want my SQL command to output something like
TimeStamp | Occurrences
-----------+------------
2017-08-31 | 4
2017-09-01 | 2
2017-09-02 | 3
I have been trying to get there from what I have so far but I haven't had luck.
I have this SQL :
SELECT
TimeStamp, COUNT(*)
FROM
myTableName
GROUP BY
TimeStamp
ORDER BY
COUNT(*) DESC -- to sort the occurrence count
but this only counts exactly same timestamps, so this doesn't output what I want it to output. I am also thinking TimeStamp has DateTime type, so I had to convert it to varchar or something first and get the substring of it.
I tried converting the TimeStamp data type to Varchar, and then get the first 10 letters of the string, so
SELECT
COUNT(*) TimeStamp
FROM
myTableName
GROUP BY
(SELECT LEFT(CONVERT(Varchar, TimeStamp, 120), 10))
ORDER BY COUNT(*) DESC
but this causes an error:
Error: Cannot use an aggregate or a subquery in an expression used for the group by list of a GROUP BY clause
Can someone please help me with this? Thank you.
SELECT CAST(TimeStamp as date), COUNT(*)
FROM myTableName
GROUP BY CAST(TimeStamp as date)
ORDER BY 2 DESC

Query for date groupings?

I have a Client table with basic demographics in rows and a date of birth row (DOB) with a DATE data type.
I'm trying to make a query that will take my entries and count how many clients are between the ages of 18-60, 61-79, 80+. I'm not sure if I'm having a brain-fart, but I can't figure out how to gather that info from my table...
So what I have is:
Last Name First Name DOB
Stein Ethel 1954-01-20
Frank Sam 1981-05-65
etc...
What I want to have is:
Ages 18-60
6
Ages 61-79
10
Ages 80+
20
Any recommendations to proceed?
Using #Alex's suggestion
declare #today datetime
set #today =getdate()
select
s as [start],
e as [end],
count(1) as [count]
from Client join
(values (0,17),(18,60),(61,79),(80,9999)) as ranges(s,e)
on datediff(yy,dob,#today) between s and e
-- where buildingid=1
group by s,e
See demo here

filter a sql statement using its column values

I have a table named 'Table1'.
It has 3 columns namely
1. vehicle Number
2. startdatetime
3. enddatetime
the table is as below->
vehicleno | startdatetime | enddatetime |
1 2013/07/16 00:00:00 2013/07/17 00:00:00
2 2013/07/16 00:00:00 2013/07/18 14:00:00
3 2013/07/17 12:19:00 2013/07/20 17:35:00
4 2013/07/19 10:24:56 2013/07/19 20:14:00
5 2013/07/15 08:10:00 2013/07/18 09:10:00
Now i want a o/p such that ,At the time of executing the query if the present datetime is between the startdatetime and enddatetime then the record should be displayed in my o/p table.
I have tried with the query..
select * from Table1 where startdatetime between '2013/07/17 00:00:00' and '2013/07/17 23:59:59' or enddatetime between '2013/07/17 00:00:00' and '2013/07/17 23:59:59'
but i didn't get the result i want.
Please help me out..
If you are looking for the current date why not use GETDATE?
Returns the current database system timestamp as a datetime value
without the database time zone offset. This value is derived from the
operating system of the computer on which the instance of SQL Server
is running.
Something like
select *
from Table1
where GETDATE() BETWEEN startdatetime AND enddatetime
SQL Fiddle DEMO
I would think you'd want to do:
select vehicleno ,startdatetime, enddatetime
from table1
where getUTCDate() between startdatetime and enddatetime
Then if you aren't in GMT you can do a dateAdd(hour, 5, getUTCDate()) if you are say EST.
It's always more correct to specify the columns you want to use in the select statement.
And at this point since we live in a global community I feel it's more appropriate to use getUTCDate() instead of just regular getDate() because getDate() just does the timezone that the server is located in and it will depend on where the server is if this works for your situation.
You can see the definition of GetUTCDate()
Try the following:
select *
from Table1
where GetDate() between startdatetime and enddatetime
GetDate() gets the current datetime
Just for the record, if you want to use literal dates in SQL, use ISO date format (YYYY-MM-DD hh:mm:ss). That is the only format guaranteed to be interpreted correctly regardless of your locale settings.

Resources