SQL Server: Find the number of substring occurrences of converted data - sql-server

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

Related

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

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

how to have date time column converted into date and displaying as 103 style

Hi i've a column the_date which is having sample data like
1900-01-01 00:00:00.000
1990-01-01 00:00:00.000
1990-01-02 00:00:00.000
1990-01-03 00:00:00.000
1990-01-04 00:00:00.000
1990-01-05 00:00:00.000
1990-01-06 00:00:00.000
1990-01-07 00:00:00.000
now i just want to select only date only and displaying it into 103 style and convert the column into Date format. i've tried this syntaxconvert(varchar,THE_DATE , 103) but then the column is not in Date format.
any help please.
This Works try it once
SELECT CONVERT(varchar,CAST(DATE_TIME AS DATE),103)AS Date_Time From <yourTable>
It's a little confusing because regardless of the datatype, you will always get the same answer with CONVERT. I'll illustrate this with 2 declared variables, 1 datetime datatype, the other date datatype:
DECLARE #mydatetime datetime = '1990-01-01 00:00:00.000'
DECLARE #mydate date = '1900-01-01'
SELECT convert(varchar,#mydatetime, 103) as mydatetime
SELECT convert(varchar,#mydate, 103) as mydate
Produces:
mydatetime
01/01/1990
mydate
01/01/1900
So you don't need to cast to date, then to 103 format.
If you don't like the time with date in your table (datetime) then you can always ALTER the column in the table to the date datatype. This can be done using SSMS or you can do the SQL:
ALTER TABLE mytable ALTER COLUMN mycolumn DATE
Where DATE is the new datatype. And then only the date is stored in the table.
Converting a string (or an equivalent database type) to another type is called "parsing". Converting another type to string is called "formatting".
The DATE or DATETIME type (or equivalent type in the front-end) does not store dates as string and has therefore no format. A number is used to represent the date internally which counts the days since a reference date (1753-01-01 for SQL-Server). The time is represented as decimal fraction.
Of course you always see the date as formatted when you open the table, because it is converted to a text for display, but it is not stored as formatted.
So, what you have to do if your date is given as text, is to parse it using the 121 format (YYYY-MM-DD HH:MI:SS.MMM (24h)) to get a DATE (or DATETIME).
CONVERT(DATE, the_date, 121) or CONVERT(DATETIME, the_date, 121)
If the_date is already of DATE (or DATETIME) type and you want to display it in the 103 format (DD/MM/YYYY)
CONVERT(VARCHAR(10), the_date, 103)
If the date is given as DATETIME type and you just want to strip off the time part and return the result as DATETIME type again, you can do
DATEADD(dd, DATEDIFF(dd, 0, the_date ), 0)
Note that no date format is involved here, since the date does never appear as text.
thanks for all your answer but for anyone who has my same query i got the solution from here
solution

SQL Server Get row value when using MAX

I have a table which holds a date field and an integer field like the example below:
Date Number
01/01/2017 9
02/01/2017 13
03/01/2017 16
04/01/2017 2
15/01/2017 4
20/01/2017 8
27/01/2017 1
I want to write a query selecting the MAX(date) where the date is <= 13/01/2017 (which would give me 04/01/2017) and return the number column value associated with it (2 in this example).. I can of course write 2 queries getting one and using the result to find the next but I hope there is another way using only one statement. It probably would help if I knew how to word this so I haven't had much luck searching for a solution..
Thank you in advance..
Derek
Use TOP 1 and Order By
select Top 1 * from yourtable where [date] <= CONVERT(DATE, '13/01/2017', 103)
order by date desc
Better to use yyyy-mm-dd format for your date input

Update partial Date time column value in sql server

I want to update date time column in my SQL server.Consider the date time column contains following values,
2015-02-13 00:00:00.000
2015-02-18 00:00:00.001
2015-02-21 00:05:00.002
2015-02-13 00:03:00.003
2015-02-19 01:00:00.004
2015-01-13 00:00:00.005
2015-01-11 00:01:00.006
2015-01-13 00:02:00.007
I want to change the only the day to 14 without making any change in other values(year,month,time). Could you please help me to write a update statement for this?
Depending on your where conditions you can use DATEADD function, like DATEADD(day, 1, column). This will not affect other parts.
If the day parts differ, you can use
column = DATEADD(day, 14-DATEPART(day, column), column)
want to update only specify date with out affecting HH:MM:SS then in filter condition use Substring also
Assume your table like this :
update table
set datecol = DATEADD(DAY,1,DATECOL)
where
datecol = SUBSTRING(DATECOL,0,CHARINDEX(' ',DATECOL))
update table1
set column1 = dateadd(dd,14, convert(datetme, CONVERT(VARCHAR(25), DATEADD(dd, -(DAY(column1)-1),column),101),112))

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