T-SQL select records for the month - sql

I have a table called logD, with a field named date (datefield type). Format is "year-month-day" IE: 2011-04-11
If today's date is 2011-07-31, I want all the records for the month of July. If today's date is 2011-02-14, I want all the records for the month of Feb and so on.
I am using SQL 2008 and reporting services to run a monthly report.

Try this:
SELECT *
FROM logD
WHERE YEAR(DATE) = YEAR(GetDate())
AND MONTH(DATE) = MONTH(GetDate())

If you have an Index on the column DATE then you can try this one:
SELECT *
FROM logD
WHERE [DATE] BETWEEN CONVERT(VARCHAR(6),GETDATE(),112)+'01' AND DATEADD(DAY,-1,DATEADD(MONTH,1,CONVERT(VARCHAR(6),GETDATE(),112)+'01'))
But, man, it looks ugly...

Try this:
DECLARE #firstOfMonth smalldatetime = dateadd(month,datediff(month,0,getdate()),0);
SELECT * FROM logD
WHERE [date] > #firstOfMonth
AND [date] < dateadd(month,1,#firstOfMonth);

Related

How to SELECT year using a WHERE clause on a DateTime type column

There is a table Saleswith data from year 2005 to year 2015
I want to query data and filter column Sales_Date with datetime data type where the year is 2013 including all other columns
SELECT *
FROM Sales
WHERE Sales_Date BETWEEN '2013-01-01' AND '2014-01-01';
is this correct or there is a function specifically to filter query by year of datetime data type
It is not correct as it includes data from 2014-01-01, which isn't a day in 2013.
Instead of between, which checks for a closed interval, use >= and < to search for an interval open at the end.
SELECT *
FROM sales
WHERE sales_date >= '2013-01-01'
AND sales_date < '2014-01-01';
You could also use year() or datepart() to extract the year like in
...
WHERE year(sales_date) = 2013;
or
...
WHERE datepart(year, sales_date) = 2013;
But that will prevent any index on sales_date to be used, which isn't good in terms of performance. So it's not the best way to query that data, the first approach with >= and < is to be preferred.
You can use the year function:
SELECT *
FROM Sales
WHERE YEAR(Sales_Date) = 2013;

SQL : Get last 3 month data (with only available data in the column), not from current month or today?

Anyone help me out on this scenario. I need to get a last 3 month data from particular column, which is not from current date but only from available date.
Ex :
I have one Table named Shop and column named OrderDate, In OrderDate i have only dates until 30-06-2017, but today's date is 07-02-2018. From this i need to get last 3 months data, which is Jun'17, May'17 and Apr'17.
If data available in till July'17 means i need result Jul'17,Jun'17 & May'17. And so on.
Any can help on this to achieve in SQL ?
Thanks in advance.
I assume that column OrderDate is of date or datetime datatype.
select * from Shop
where OrderDate >
(select dateadd(month, -3, max(OrderDate)) from Shop)
I think the easiest way to get this is to select the largest date in that table and use that to create the filter.
So;
Select *
from table
where date >
Dateadd
('m', -3,
( Select Max (date) from table)
)
Apologies in advance for poor formatting
You will have to find the maximum date in the table and use that:
select s.*
from Shop s,
(select convert(date,
format(
dateadd(MONTH, -3, max(OrderDate)), 'yyyyMM01')
,112) as fromDate from Shop) md
where s.OrderDate >= md.fromDate

Calculate totals of field based on current fiscal year only - SQL

I have seen many examples regarding calculating the sum of fields using the fiscal year, but I can not find one that fits my needs. What I am trying to do is get just the current fiscal year totals for a field using SQL Query. The fields I have is userid, startdate, total_hours, and missed_hours. Here is the query I have so far:
SELECT
userid,
SUM(total_hours) - SUM(missed_hours) AS hours
FROM mytable
GROUP BY userid
This works great, but all I need is the total number of hours for the current fiscal year for each of the userid's. Our fiscal year runs from July to June. I only need the current fiscal year and I need it to start over again this coming July.
Assuming this is SQLServer, try:
SELECT userid, SUM(total_hours) - SUM(missed_hours) AS hours
FROM mytable
WHERE startdate >= cast( cast(year(dateadd(MM,-6,getdate())) as varchar(4)) +
'-07-01' as date ) and
startdate < cast( cast(year(dateadd(MM, 6,getdate())) as varchar(4)) +
'-07-01' as date )
GROUP BY userid
Add a where clause:
FROM mytable
WHERE startdate >= '2011-07-01'
GROUP BY userid
Or with the start of the year dynamically:
where startdate >= dateadd(yy, datepart(yy, getdate())-2001, '2000-07-01')
Maybe something like this:
SELECT
userid,
SUM(total_hours) - SUM(missed_hours) AS hours
FROM
mytable
WHERE
MONTH(startdate) BETWEEN 6 AND 7
AND YEAR(startdate) IN (2011,2012)
GROUP BY userid
For the solution, two additional information is needed
the name of the date column
the vendor type of RDBMS you are using
I supposed your date column is date_col and you are using MySQL
SELECT
userid,
SUM(total_hours) - SUM(missed_hours) AS hours
FROM mytable
WHERE date_col between STR_TO_DATE('01,7,2011','%d,%m,%Y') and STR_TO_DATE('01,7,2010','%d,%m,%Y')
GROUP BY userid

SQL get records in the same week

I have a table that contains records with a column indicates the Date. Given a record, I would like to select all records that are in the same week as the record. How can SQL do that?
I should say that I'm using SQLite.
You can use DATEPART with wk to get the current week. Then just check for equality.
In this case, I have also checked yy to make sure that you do not check the year of a previous week.
SELECT *
FROM TABLE
WHERE DATEPART(wk, TABLE.DATECOLUMN)
= DATEPART(wk, (SELECT DATECOLUMN FROM TABLE WHERE ID = GivenID))
AND DATEPART(yy, TABLE.DATECOLUMN) = DATEPART(yy, (SELECT DATECOLUMN FROM TABLE WHERE ID = GivenID))
UPDATE FOR SQLITE
To do this in SQLLite, Refer to this SO question and then this article that states %W is what you use to get week and %Y for year. Which gives you:
SELECT *
FROM TABLE
WHERE STRFTIME('%W', TABLE.DATECOLUMN)
= STRFTIME('%W', (SELECT DATECOLUMN FROM TABLE WHERE ID = GivenID))
AND STRFTIME('%Y', TABLE.DATECOLUMN)
= STRFTIME('%Y', (SELECT DATECOLUMN FROM TABLE WHERE ID = GivenID))
Use the datediff() function:
datediff(ww,start_date,end_date) < 1
You can use BETWEEN to specify the records you want.
SELECT * FROM records WHERE datecolumn between 'YYYY/MM/DD' AND 'YYYY/MM/DD'

SQL Current month/ year question

So I have a table that has the month and year broken down, for example field called Month has the number 7 in it (this month) and the Year field has 2011. Theres also additional months years, etc. How can I query this to show just the current year, month?
In SQL Server you can use YEAR, MONTH and DAY instead of DATEPART.
(at least in SQL Server 2005/2008, I'm not sure about SQL Server 2000 and older)
I prefer using these "short forms" because to me, YEAR(getdate()) is shorter to type and better to read than DATEPART(yyyy, getdate()).
So you could also query your table like this:
select *
from your_table
where month_column = MONTH(getdate())
and year_column = YEAR(getdate())
This should work for SQL Server:
SELECT * FROM myTable
WHERE month = DATEPART(m, GETDATE()) AND
year = DATEPART(yyyy, GETDATE())
This should work in MySql
SELECT * FROM 'my_table' WHERE 'month' = MONTH(CURRENT_TIMESTAMP) AND 'year' = YEAR(CURRENT_TIMESTAMP);
How about:
Select *
from some_table st
where st.month = to_char(sysdate,'MM') and
st.year = to_char(sysdate,'YYYY');
should work in Oracle. What database are you using? I ask because not all databases have the same date functions.
DECLARE #CMonth int=null
DECLARE #lCYear int=null
SET #lCYear=(SELECT DATEPART(YEAR,GETDATE()))
SET #CMonth=(SELECT DATEPART(MONTH,GETDATE()))
select *
from your_table
where MONTH(mont_year) = MONTH(NOW())
and YEAR(mont_year) = YEAR(NOW());
Note: (month_year) means your column that contain date format. I think that will solve your problem. Let me know if that query doesn't works.