SQL Select data by this week - sql

Hi how do I get the data by current week?
Select * from Transaction where transactionDate ....

In SQL Server based on week of year. Please see DATEPART for ##DATEFIRST etc. for example, this is all trades since Sunday in US/UK settigs:
WHERE DATEPART(week, transactionDate) = DATEPART(week, GETDATE())
Edit:
For Access, use this DatePart and use "ww" for the part of date you want.
In answer to the comment, "week" is not a variable; it's the bit of the date you want
So:
WHERE DatePart("ww", transactionDate) = DatePart("ww", GETDATE())

In Microsoft Access
Last n days:
SELECT *
FROM Transaction
WHERE transactionDate >=Date()-7
If you have indexes and this type of difference suits, it will be faster because it is sargable
This week by week difference:
SELECT *
FROM Transaction
WHERE DateDiff("w",[transactionDate],Date())=0
BTW It is considered bad practice to use *
DateDiff: http://office.microsoft.com/en-us/access/ha012288111033.aspx

Simple but portable:
SELECT *
FROM Transaction
WHERE transactionDate >= ?
AND transactionDate <= ?
Calculate the two parameters in your server-side code to whatever definition of 'week' you need.

In IBM DB2
SELECT *
FROM Transaction
WHERE transactionDate BETWEEN CURRENT TIMESTAMP - 7 days AND CURRENT TIMESTAMP;

In Access, if you want to run a query to find records that fall in the current week, use
SELECT *
FROM table
WHERE table.DateField Between (Date()-Weekday(Date())+1) And (Date()-Weekday(Date())+7);
That runs Sunday through Saturday. Use +2 and +6 instead if you want the workweek.

mySQL (standard date stamp)
SELECT *
FROM Transaction
WHERE WEEK(NOW())=WEEK(transactionDate);
mySQL (unix timestamp stamp)
SELECT *
FROM Transaction
WHERE WEEK(NOW())=WEEK(FROM_UNIXTIME(transactionDate));
Bit of a unoptimized query. Could be a more efficient way.
Note: This isn't a rolling 7 days. Just the current week of the year.
EDIT: Sorry I didn't see the ms-access tag. ignore all of this :|

Related

SQL Date less than few days from today

I have a table in which I have emails to users and I want to make request to take users who are dated less than two days from today. How can make this?
This is my SQL table :
CREATE TABLE vacation_users(EMAIL VARCHAR(255), STARTDATE DATE, ENDDATE DATE);
The answer is this. I use HSQLDB and this is answer.
SELECT * FROM vacation_user WHERE (ENDDATE < (SYSDATE + 2 DAY));
Try this(not tested):
SELECT EMAIL from vacation_users
WHERE ENDDATE < DATEADD(day, +2, CURRENT_DATE) AND ENDDATE > CURRENT_DATE
It selects the mails, which have the enddate, which is equal bigger than current date, but smaller than current date + 2.
EDIT: I updated the answer, since the OP informed me about the DB, which is used. If CURRENT_DATE also doesn't work, you can try another from the built-in functions.
select *
from vacation_users
where STARTDATE = dateadd(day,datediff(day,2,STARTDATE),0)
That depends on a database you use, but the principle is more or less the same.
In Oracle, you'd do something like
select email
from vacation_users
where startdate < sysdate - 2;
which returns you to exact time 2 days ago (if it is 09:53 today, it'll be 09:53 2 days ago). Depending on what you really need, you might need to TRUNCate those values (so that you'd get date without its time component) or apply some other function or principle, regarding possible index impact etc.
Though, "dated less than two days from today" is ... what exactly? Is it a STARTDATE or ENDDATE (or some combination of those two)?
SELECT *
FROM vacation_users
WHERE (DATEADD(day,2,ENDDATE)) < (CONVERT(date, SYSDATETIME()))

T-SQL: How to get all records prior to the first day of the current month?

Using SQL Server: I am trying to find all records prior to the first day of the current month and set this as a parameter in an SSRS report (so I can't use a static value).
So, I need all records prior to the first day of the each current month going forward in column CREATEDDATETIME ('yyyy-mm-dd').
I have seen a lot of threads on how to find records for a specific month and various other searches but none specifically related to the above. Interested to see if the EOMONTH function will be of use here.
Thanks for the help and advice.
Here is an expression to use EOMONTH() function with optional parameter -1.
Explanations:
DateAdd: add 1 day to expression
getdate is current date
EOMONTH is end day of a given month; however, if you put an optional integer -1, this would mean last month
Thus: first day of current month is add one day to end of day last month
SELECT DATEADD(DAY,1,EOMONTH(getdate(),-1));
Result: 2018-04-01
SO in your query:
select *
from table
where CREATEDDATETIME < DATEADD(DAY,1,EOMONTH(getdate(),-1));
I would use datefromparts():
select t.*
from t
where CREATEDDATETIME < datefromparts(year(getdate()), month(getdate()), 1);
There's already two other answers that work, but for completeness here is a third common technique:
SELECT *
FROM [table]
WHERE CREATEDDATETIME < dateadd(month, datediff(month,0, current_timestamp), 0)
You might also get answers suggesting you build the date using strings. Don't do that. It's both the least efficient and most error prone option you could use.
all three answers are great, how ever you may find that it will select all the data prior to the 1st day of the current month until the 1st Createdate. This could cause the report to take forever to run, Maybe building in a limitation to the code I would use something like this to build a report that gives details for last month only.
Select [columns]
from [source]
where [Createdate] between
/*First day of last Month*/
DATEADD(mm, DATEDIFF(mm, 0, Getdate())-1, 0 and
/*First day of this Month*/
dateadd(mm,datediff(mm,0,Getdate()),0)

DB2 Between Statement for Last Sunday to This Coming Saturday

I am curious why this does not work:
SELECT *
FROM TABLE
WHERE DATE_TIME_COLUMN BETWEEN
current date - int((dayofweek(current date))-1)
AND
current date + int(7-(dayofweek(current date)))
When this gives me exactly what I want:
select current date - int((dayofweek(current date))-1) days from sysibm.sysdummy1)
select current date + int(7-(dayofweek(current date))) days from sysibm.sysdummy1)
The above two will yield the correct dates that I want my specific date time column to be in between. What am I missing here?
SELECT *
FROM TABLE
WHERE DATE_TIME_COLUMN BETWEEN
current date - ((dayofweek(current date))-1) DAYS
AND
current date + (7-(dayofweek(current date))) DAYS
You have to signify that you are reducing DAYS from current date as shown above.
"Does not work" is a little vague :). Your first query is missing the DAY part to tell DB2 what part you're doing the date math on.
However, it kind of sounds like you might want to use the WEEK scalar function:
SELECT *
FROM TABLE
WHERE WEEK(DATE_TIME_COLUMN) = WEEK(CURRENT_DATE)
AND YEAR(DATE_TIME_COLUMN) = YEAR(CURRENT_DATE)

SQL query for selecting specific date range (such as the current month only)

I am working in SQL Server 2012.
I am trying to collect all data for the current month (2015-07) and group them. When I run this query it selects only the current day.
SELECT
YEAR, MONTH, IDWHSE, IDLOCATION, IDCUST,
SUM(PALLETDAYS) AS PALLETDAYS,
COUNT(*) AS LOCATIONDAYS
FROM
[METRICS].[dbo].[DailyData]
WHERE
DATE = CONVERT(date, DATEADD(MM, 0, GETDATE()))
GROUP BY
YEAR, MONTH, IDWHSE, IDLOCATION, IDCUST, PALLETDAYS
Thanks in advance
Gerry
Try this:
SELECT
YEAR, MONTH, IDWHSE, IDLOCATION, IDCUST,
SUM(PALLETDAYS) AS PALLETDAYS,
COUNT(*) AS LOCATIONDAYS
FROM
[METRICS].[dbo].[DailyData]
WHERE
MONTH(DATE) = MONTH(SYSDATETIME())
GROUP BY
YEAR, MONTH, IDWHSE, IDLOCATION, IDCUST, PALLETDAYS
By using the MONTH() function, you get the month number - both of your column Date (which is a really horribly bad name for a column, since DATE is also a reserved keyword for a datatype in SQL Server 2012 - try to use something more meaningful than just Date!) and the current date (I prefer the SYSDATETIME() function over GETDATE())

Getting week number of date in SQL

Is there a way to get the week number of a date with SQL that is database independent?
For example to get the month of a date I use:
SELECT EXTRACT(MONTH FROM :DATE)
But the EXTRACT function doesn't know about weeks in SQL92.
Please pay attention to the fact that I want a solution that is database independent! Do not misinterpret this as a question regarding MS SQL Server.
There doesn't appear to be a single standard SQL function to extract the week number from a date - see here for a comparison of how different SQL dialects can extract different dateparts from date fields.
You can try this.
declare #date datetime
select #date='2013-03-15 00:00:00'
select 'Week No: '+ convert(varchar(10),datepart(wk,#date)) as weekno
Try this one :
SELECT DATENAME(yy,GETDATE())+RIGHT(DATENAME(wk,GETDATE()),2)
To understand DATENAME, please follow this link : sqltutorials.blogspot.be/2007/05/sql-datename.html and for the right, suite101.com/article/sql-functions-leftrightsubstrlengthcharindex-a209089 . There are examples to better understand ;-) It will work on MS and other sql servers normally ;-)
The only db independent solution I see is to get the number of days between today and Jan 1 of curr. year. Then divide it by 7 and round it up. There is 73 days from Jan 1 till today, which gives 10.43 as week number. The ISO week number is 11.
Correction: the number of days between last day of the current week and Jan 1 of curr. year. In this case the ISO week is 10, and 68/7 = 10 (rounded).
The best idea I found is
SELECT ROUND(((DAY(NOW())-1)/7)+1)
select (DATEPART(yyyy , CAST(GETDATE() AS datetime)) * 100 +
DATEPART(ww , CAST(GETDATE() AS datetime))) as week