convert date column into week number, date, month, year - sql

I have a date column Time in the database which i want to convert into 4 new columns
Week
day
month
year
I am using something like this on my test database
SELECT DATEPART(wk,`Time`), DATEPART(dd,`Time`),DATEPART(mm,`Time`),DATEPART(wk,`yyyy`), FROM `Test` WHERE 1
What is wrong in it?

In Sql server, you don't wrap your identifiers with `.
However, since Time is a data type in sql server, I've wrapped it with []:
Try this query instead:
SELECT DATEPART(Week,[Time]) As [Week],
DATEPART(Day,[Time]) As [Day],
DATEPART(Month,[Time]) As [Month],
DATEPART(Year,[Time]) As [Year]
FROM Test
Also, there was an extra comma after the last element in the select clause,
and the Where clause was meaningless, so I've removed it.

You have wrong syntax to fetch year and also extra (,) before From clause
Try as below:
SELECT DATEPART(wk,GETDATE()), DATEPART(dd,GETDATE()),DATEPART(mm,GETDATE()),DATEPART(yy,GETDATE())
SELECT DATEPART(week,GETDATE()), DATEPART(day,GETDATE()),DATEPART(month,GETDATE()),DATEPART(year,GETDATE())
SELECT DATEPART(wk,[Time]), DATEPART(dd,[Time]),DATEPART(mm,[Time]),DATEPART(yy,[Time]) From TableName

select datepart(week,GETDATE()) as [week]
, datepart(DAY,GETDATE()) as [DAY]
, datepart(month,GETDATE()) as [month]
,datepart(year,GETDATE()) as [year]

You could also simplify it by using YEAR,MONTH,DAY like this:
SELECT
YEAR(GETDATE()),
MONTH(GETDATE()),
DAY(GETDATE()),
DATEPART(WEEK,GETDATE())

Related

Selecting group of years from date field

I'm trying to get a list of years from a date field that's stored as an nvarchar so am thinking doing a subquery to convert the date then select the year is the best way to go but having a hard time setting it up.
select datepart(yyyy,
(
SELECT convert(date,'21-02-12 6:10:00 PM',5) datenum
)
) as [year]
from SalesReport_AllDBs
group by datepart(yyyy, [datenum])
Any advice would be helpful to get this set up correctly
The subquery should go in your FROM clause:
SELECT datepart(yyyy, mydate) as datenum
FROM (SELECT convert(date, yourdatestringfield ,5) as myDate FROM SalesReport_AllDBs) as years
GROUP BY datepart(yyyy,mydate);
Or in one query without a subquery, which is a lot nicer looking:
SELECT datepart(convert(date, yourdatestringfield ,5)) as datenum
FROM SalesReport_AllDBs
GROUP BY datenum
You should really just fix the table to hold dates instead of strings though. This is just going to lead to some nightmare scenarios and a slow slow query.
select distinct year(cast([datenum] as date)) year
from SalesReport_AllDBs

Select "YYYY" component only from DateTime column

Using SQLCe, I have a column of DateTime type. I would like to filter just by year. Is it possible or should I store year separately, which seems to me redundant?
E.g. get distinct results of 2010,2011,2013.
Thanks
think you have the DATEPART function (but not the YEAR function)
so
select DatePart(yyyy, <yourDateTime>)
or if that's for ordering, of course
order by DatePart(yyyy, <yourDatetime>)
EDIT
select max(InvoiceID)
from yourTable
where DatePart(yyyy, IssuedDate) = 2013
You can use the DATEPART function to return the year for that column:
SELECT DATEPART(yyyy, datetimecolumn) FROM YourTable
You can then filter with a where clause:
WHERE datetimecolumn = 2014
The usual way to do this is to use a range filter:
select *
from table
where datecolumn >= '2012/01/01' and datecolumn < '2013/01/01'
This has the benefit that any index you may have on datecolumn can be used.
Since the answer you accepted shows that you only care about one single year, your objection to this answer doesn't really apply.
select max(InvoiceID)
from table
where IssuedDate >= '2012/01/01' and IssuedDate < '2013/01/01'
will work just fine.

How can I group by date time column without taking time into consideration

I have a bunch of product orders and I'm trying to group by the date and sum the quantity for that date. How can I group by the month/day/year without taking the time part into consideration?
3/8/2010 7:42:00 should be grouped with 3/8/2010 4:15:00
Cast/Convert the values to a Date type for your group by.
GROUP BY CAST(myDateTime AS DATE)
GROUP BY DATEADD(day, DATEDIFF(day, 0, MyDateTimeColumn), 0)
Or in SQL Server 2008 onwards you could simply cast to Date as #Oded suggested:
GROUP BY CAST(orderDate AS DATE)
In pre Sql 2008 By taking out the date part:
GROUP BY CONVERT(CHAR(8),DateTimeColumn,10)
CAST datetime field to date
select CAST(datetime_field as DATE), count(*) as count from table group by CAST(datetime_field as DATE);
GROUP BY DATE(date_time_column)
Here's an example that I used when I needed to count the number of records for a particular date without the time portion:
select count(convert(CHAR(10), dtcreatedate, 103) ),convert(char(10), dtcreatedate, 103)
FROM dbo.tbltobecounted
GROUP BY CONVERT(CHAR(10),dtcreatedate,103)
ORDER BY CONVERT(CHAR(10),dtcreatedate,103)
Here is the example works fine in oracle
select to_char(columnname, 'DD/MON/yyyy'), count(*) from table_name group by to_char(createddate, 'DD/MON/yyyy');
Well, for me it was pretty much straight, I used cast with groupby:
Example:
Select cast(created_at as date), count(1) from dbname.tablename GROUP BY cast(created_at as date)
Note: I am using this on MSSQL 2016.
I believe you need to group by , in that day of the month of the year .
so why not using TRUNK_DATE functions .
The way it works is described below :
Group By DATE_TRUNC('day' , 'occurred_at_time')

sort distinct date column

I need distinct year and month from date column which would be sorted by same column.
I have date coulmn with values like (YYYY/MM/DD)
2007/11/7
2007/1/8
2007/11/4
2007/12/3
2008/10/4
2009/11/5
2008/5/16
after having query, it should be
2007/1/1
2007/11/1
2007/12/1
2008/5/1
2008/10/1
2009/11/1
This doesn't seems to be working
SELECT distinct (cast(year(datecol) as nvarchar(20) ) +
'/'+ cast(month(datecol) as nvarchar(20) ) + '/1') as dt1
FROM Table
ORDER BY dt1
Soemthing like this would work on MS SQL Server:
select
distinct
dateadd(day, -1 * DAY(datefield) + 1, datefield)
From
datetable
order by
dateadd(day, -1 * DAY(datefield) + 1, datefield)
The DATEADD function call basically subtracts (day-1) DAYS from the current date --> you always get the first of whatever month that date is in.
Sort by it and you're done! :-)
ADditionally, you could also add this functionality to your table as a "computed column" and then use that for easy acccess:
alter table yourTable
add FirstOfMonth As DATEADD(day, -1 * DAY(datefield) + 1, datefield) persisted
Then your query would be even simpler:
SELECT DISTINCT FirstOfMonth
FROM YourTable
ORDER BY FirstOfMonth
Marc
When dealing with dates in SqlServer avoid using cast like this - the resulting format will change depending on server config.
Instead use convert and choose a format (for instance 112) that adds leading zeros to the month.
Anil,
Do you also have time part in the dates ? What dataType are you using for the column ? Are you
using DateTime dataType or Char ?
This works for me
SELECT DISTINCT (DateField) AS Date FROM DateTable ORDER BY 1

Execute count(*) on a group-by result-set

I am trying to do a nice SQL statement inside a stored procedure.
I looked at the issue of seeing the number of days that events happened between two dates.
My example is sales orders: for this month, how many days did we have sales orders?
Suppose this setup:
CREATE TABLE `sandbox`.`orders` (
`year` int,
`month` int,
`day` int,
`desc` varchar(255)
)
INSERT INTO orders (year, month, day, desc)
VALUES (2009,1,1, 'New Years Resolution 1')
,(2009,1,1, 'Promise lose weight')
,(2009,1,2, 'Bagel')
,(2009,1,12, 'Coffee to go')
For this in-data the result should be 3, since there has been three days with sale.
The best solution I found is as below.
However, making a temporary table, counting that then dropping it seemes excess. It "should" be possible in one statement.
Anyone who got a "nicer" solution then me?
/L
SELECT [Year], [Month], [Day]
INTO #Some_Days
FROM Quarter
WHERE Start >= '2009-01-01' AND [End] < '2009-01-16'
GROUP BY [Year], [Month], [Day]
SELECT count(*) from #Some_Days
Apologies if I'm misunderstanding the question, but perhaps you could do something like this, as an option:
SELECT COUNT(*) FROM
(SELECT DISTINCT(SomeColumn)
FROM MyTable
WHERE Something BETWEEN 100 AND 500
GROUP BY SomeColumn) MyTable
... to get around the temp-table creation and disposal?
There are two basic options which I can see. One is to group everything up in a sub query, then count those distinct rows (Christian Nunciato's answer). The second is to combine the multiple fields and count distinct values of that combined value.
In this case, the following formula coverts the three fields into a single datetime.
DATEADD(YEAR, [Quarter].Year, DATEADD(MONTH, [Quarter].Month, DATEADD(DAY, [Quarter].DAY, 0), 0), 0)
Thus, COUNT(DISTINCT [formula]) will give the answer you need.
SELECT
COUNT(DISTINCT DATEADD(YEAR, [Quarter].Year, DATEADD(MONTH, [Quarter].Month, DATEADD(DAY, [Quarter].DAY, 0), 0), 0))
FROM
Quarter
WHERE
[Quarter].Start >= '2009-01-01'
AND [Quarter].End < '2009-01-16'
I usually use the sub query route, but depending on what you're doing, indexes, size of table, simplicity of the formula, etc, this Can be faster...
Dems.
How about:
SELECT COUNT(DISTINCT day) FROM orders
WHERE (year, month) = (2009, 1);
Actually, I don't know if TSQL supports tuple comparisons, but you get the idea.
COUNT(DISTINCT expr) is standard SQL and should work everywhere.
You should use nested Select statements. Inner one should contain group by clause, and the outer one should count it. I think "Christian Nunciato" helped you already.
Select Count(1) As Quantity
From
(
SELECT [Year], [Month], [Day]
INTO #Some_Days
FROM Quarter
WHERE Start >= '2009-01-01' AND [End] < '2009-01-16'
GROUP BY [Year], [Month], [Day]
) AS InnerResultSet
SELECT [Year], [Month], [Day]
FROM Quarter
WHERE Start >= '2009-01-01' AND [End] < '2009-01-16'
GROUP BY [Year], [Month], [Day]
COMPUTE COUNT(*)