Return records less than date - sql

I have a table where 2 columns are called Month and Year and are both INT. I need to return all the records that are less than the date provided.
So if I pass the following parameters #Month = 8 and #Year = 2017, I would like to return all records before August 2017. What is the best way to achieve this?
SELECT * FROM testTable
WHERE year <= #Year AND
month < #Month
is my current SQL. This won't work if I need to display the record that is November 2014

Compare them as dates. Like this:
SELECT * FROM testTable
WHERE DATEFROMPARTS(year, month, 1) <= DATEFROMPARTS(#Year, #Month, 1)

Pass The Parameter as Date. Like
DECLARE #MyDate DATE = '08-01-2014'
Now you can go for either of the below
SELECT
*
FROM YourTable
WHERE CAST(ConCAT([Monnth],'-01-',[Year]) AS DATE) = #MyDate
Or
SELECT
*
FROM YourTable
WHERE [Year] = YEAR(#MyDate)
AND [Month] = MONTH(#MyDate)

You can use DATEPART function of SQL Server
SELECT * FROM testTable
WHERE YEAR<= DATEPART(yy,yourdate) AND
MONTH < DATEPART(mm,yourdate)

It would be better to convert data types and query further.
DECLARE #testtable TABLE (id INT identity(1, 1), name VARCHAR(100), year INT, month INT)
INSERT INTO #testtable (name, year, month)
SELECT 'me', '2014', 10
UNION
SELECT 'you', '2017', 08
UNION
SELECT 'us', '2015', 10
UNION
SELECT 'Him', '2017', 10
UNION
SELECT 'Her', '2018', 1
SELECT *
FROM #testtable
WHERE CONCAT (year, '-', right('00' + cast(Month AS VARCHAR(2)), 2), '-', '01')
< = '2017-08-01'

Related

SQL Server 2008

Sorry for my English...
I Iave a table with column
project, month, year
abc 2 2017
xyz 5 2017
abc 3 2017
abc 5 2017
abc 1 2018
How can I search project abc with month = 2 year = 2017 until month = 1 year = 2018
As far as I know, SQL Server 2008 cannot use concat function
Use math comparison:
SELECT * FROM table1
WHERE (year * 12 + month) BETWEEN (2017 * 12 + 1) AND (2018 * 12 + 1)
Try this:
Select *
From YourTable
Where DATETIMEFROMPARTS(year, month, 1, 1, 1, 1, 1)
between '2017-02-01' And '2018-01-01'
I have edited the code to account for the leading zero in the month.
Declare #temp Table
(
project varchar(50),
month int,
year int
);
Insert Into #temp
(project, month, year)
Values ('abc', 2, 2017)
Insert Into #temp
(project, month, year)
Values ('xyz', 5, 2017)
Insert Into #temp
(project, month, year)
Values ('abc', 3, 2017)
Insert Into #temp
(project, month, year)
Values ('abc', 5, 2017)
Insert Into #temp
(project, month, year)
Values ('abc', 1, 2018)
Insert Into #temp
(project, month, year)
Values ('xxx', 5, 2010)
Insert Into #temp
(project, month, year)
Values ('xxx', 12, 2018)
Declare #FromYear int = 2010;
Declare #FromMonth int = 04;
Declare #ToYear int = 2018;
Declare #ToMonth int = 05;
Select *
From #temp
Where Convert(varchar, year) + right('00' + Convert(varchar, month), 2) Between '201004' and '201805'
How can I search project abc with month = 2 year = 2017 until month = 1 year = 2018
You can use
SELECT *
FROM T
WHERE (([Year] * 10) + [Month]) BETWEEN 20172 AND 20181
AND
project = 'abc';
Demo

SQL Query : How to get date reference of Month And Year Column?

I need a help to change the Month & Year column as Date in Result.
Ex :
Table Name : AA
Month Year
4 2016
5 2015
Result Should Be:
01-04-2016
01-05-2015
I need a SQL query for this? Can any one help me out?
Try like this,
DECLARE #AA TABLE (
Month INT
,Year INT
)
INSERT INTO #AA (
Month
,Year
)
VALUES (
4
,2016
)
,(
5
,2015
)
SELECT convert(DATE, convert(VARCHAR(50), year * 10000 + month * 100 + 01)) AS DATE
FROM #AA
Try this code:
select '01-'+cast([month] as nvarchar) + '-'+cast([Year] as nvarchar)
from YourTable
Assuming int data types:
DECLARE #Month int = 4, #Year int = 2016
SELECT CAST(CAST(#Year * 10000 + #Month * 100 + 01 As char(8)) as date)
Assuming char/varchar data types:
DECLARE #MonthString varchar(2) = 4, #YearString char(4) = 2016
SELECT CAST(#YearString +'-'+ RIGHT('00' + #MonthString, 2) + '-01' as date)
Results in both cases:
2016-04-01 -- (Date data type)
Add square brackets for the reserve keywords:
DECLARE #AA TABLE ([Month] INT, [Year] INT);
INSERT INTO #AA ([Month], [Year]) VALUES
(4, 2016),
(5, 2015);
SELECT '01-' + RIGHT('00' + CAST([MONTH] AS VARCHAR), 2) + '-' + CAST([Year] AS VARCHAR)
FROM #AA
Result:
01-04-2016
01-05-2015
DECLARE #Table1 TABLE
(Month int, Year int)
;
INSERT INTO #Table1
(Month, Year)
VALUES
(4, 2016),
(5, 2015)
;
select '01'+'-'+RIGHT('000'+CAST(Month AS VARCHAR(3)),2)+'-'+CAST(Year AS VARCHAR) from #Table1
Do not do varchar convertions. Use like below
declare #t table([Month] int,[Year] int)
insert into #t
select 4, 2016 union all
select 5, 2015
select dateadd(month,month-1,dateadd(year,[year]-1900,0)) from #t
You can use concat function to acieve this
SELECT CONCAT('01-',year,'-',month) as req_date from tableName
try this:
declare #y varchar(4)='2015'
declare #m varchar(2)='5'
--try_prase is available starting sql 2012
print try_parse('01-'+#m+'-'+#y as datetime using 'en-us')
print convert(datetime,'01-'+#m+'-'+#y,121)

SQL sorting month end (mmm-yy) starting with April

In SQL I am trying to convert dates to mmm-yy and then sort starting with April as the first month. So far I have managed to converted the date to mmm-yy using
SELECT
LNAME as Location,
SUBSTRING( CONVERT( VARCHAR(11), MonthEnd, 113), 4, 8) AS [MonthEnd],
CAST (TYPEDESC as VARCHAR(20)) as 'Factory',
Sum(Tonnes) as Tonnes
FROM (
SELECT
EOMONTH(X_DELIVERY_DATE) as MonthEnd,
...
but I cannot complete the final step, all I get is the date sorted alphabetically. If someone could please help!!
Let's say that you use SQL Server:
DECLARE #Temp TABLE
(
MonthEnd DATETIME
)
INSERT #Temp VALUES
('2015/01/01'),
('2015/02/01'),
('2015/03/01'),
('2015/04/01'),
('2015/05/01'),
('2015/06/01'),
('2015/07/01'),
('2015/08/01'),
('2015/09/01'),
('2015/10/01'),
('2015/11/01'),
('2015/12/01'),
('2016/01/01'),
('2016/02/01'),
('2016/03/01'),
('2016/04/01'),
('2016/05/01'),
('2016/06/01'),
('2016/07/01'),
('2016/08/01'),
('2016/09/01'),
('2016/10/01'),
('2016/11/01'),
('2016/12/01')
SELECT MonthEnd, SUBSTRING(CONVERT(VARCHAR(11), MonthEnd, 113), 4, 8)
FROM #Temp
ORDER BY YEAR(MonthEnd), (MONTH(MonthEnd) + 8) % 12
You can play with the DATEPART function
DATEPART(month, '10/5/2015')
And try this calculation:
SELECT (DATEPART(year, '3/5/2015') * 100) +
(CASE WHEN DATEPART(month, '3/5/2015') > 3
THEN DATEPART(month, '3/5/2015') - 4
ELSE DATEPART(month, '3/5/2015') + 9
END);

SQL Server find the last week of the last 2 months

INSERT INTO #blah (ID, Date)
VALUES (123, '11/12/2012')
VALUES (124, '11/30/2012')
VALUES (125, '11/28/2012')
VALUES (126, '12/1/2012')
VALUES (127, '12/30/2012')
VALUES (128, '12/25/2012')
VALUES (129, '12/26/2012')
I want to get rows where the date is the last week of the respective month going back two months. This month is Jan 2013, so i want the last week of Dec 2012 and Nov 2012.
The ultimate option would be the last full week of a month example: dec 2012 = 12/23-12/29 but for now ill take the last 7 days of the month.
I know how to get the last two months but unsure how to get the last week of the respective month..
select
*
from
#blah
where
dateDiff(month,date,getdate()) < 2 ---only look at the last two months
This meets the stated requirement (last full week of previous two months):
SET DATEFIRST 1;
DECLARE #s DATE = GETDATE(), #s1 DATE, #s2 DATE;
SET #s = GETDATE();
-- last day of last month:
SET #s1 = DATEADD(DAY, -DAY(#s), #s);
-- last day of previous month:
SET #s = DATEADD(MONTH, -1, #s);
SET #s2 = DATEADD(DAY, -DAY(#s), #s);
SELECT
#s1 = DATEADD(DAY, -7, DATEADD(DAY, -DATEPART(WEEKDAY, #s1) % 7, #s1)),
#s2 = DATEADD(DAY, -7, DATEADD(DAY, -DATEPART(WEEKDAY, #s2) % 7, #s2));
SELECT col1, col2, etc.
FROM dbo.table
WHERE
(date_column >= #s1 AND date_column < DATEADD(DAY, 7, #s1)
OR
(date_column >= #s2 AND date_column < DATEADD(DAY, 7, #s2);
To make this more dynamic (you should do your best to state these requirements FIRST, not after people have put in a bunch of work), you can say:
DECLARE #NumberOfMonthsIReallyWanted INT = 3;
DECLARE #i INT = 1, #d DATE = GETDATE();
DECLARE #t TABLE(d DATE);
WHILE #i <= #NumberOfMonthsIReallyWanted
BEGIN
SET #d = DATEADD(MONTH, -#i, #d)
INSERT #t(s) SELECT DATEADD(DAY, -7, DATEADD(DAY,
-DATEPART(WEEKDAY, DATEADD(DAY, -DAY(#d), #d)) % 7,
DATEADD(DAY, -DAY(#d), #d)));
SET #i += 1;
END
SELECT src.col1, src.col2, etc.
FROM dbo.table AS src
INNER JOIN #t AS t
ON src.date_column >= t.d AND src.date_column < DATEADD(DAY, 7, t.d);
Please don't let anyone convince you to use LIKE for date comparison queries. Not only does this kill sargability (meaning no index can be used), but, for a problem like this, how do you determine what string patterns to match? The difficulty is not in constructing the WHERE clause, but rather what to fill in for the magic (Your Dates go here) placeholder. And when you do find the range of dates, do you really want 14 individual LIKE expressions? I wouldn't.
declare #blah table (ID int, [Date] datetime)
INSERT INTO #blah (ID, [Date])
select 123, '20121112'
union select 124, '20121130'
union select 125, '20121128'
union select 126, '20121201'
union select 127, '20121230'
union select 128, '20121225'
union select 129, '20121226'
select ID, [Date], datepart(week, [Date])
from #blah
where
datediff(month, [Date], getdate()) in (1,2)
and
datepart(week, [Date]) = datepart(
week,
dateadd(
day,
-datepart(day,dateadd(month, 1, [Date])),
dateadd(month, 1, [Date])))
This works in Oracle - may give you some ideas and hopefully helps:
-- Last weeks of last two months --
SELECT mydate
, TRUNC(mydate, 'iw') wk_starts
, TRUNC(mydate, 'iw') + 7 - 1/86400 wk_ends
, TO_NUMBER (TO_CHAR (mydate, 'IW')) ISO_wk#
FROM
( -- Last week = Last day of the year (hardcoded) - 1 week --
SELECT(CASE WHEN start_date = To_Date('12/31/2012', 'mm/dd/yyyy') THEN start_date-7 ELSE start_date END) mydate
FROM
( -- Last 2 months --
SELECT Add_Months(Last_Day(Trunc(SYSDATE)), - LEVEL) start_date
FROM dual
CONNECT BY LEVEL <= 2
)
)
/
This is somewhat dependent on your sql server. This example is similar to Oracle. Each server has its own functions, like SYSDATE and NOW.
For example.
SELECT * from blah WHERE TO_CHAR(TRUNC(data), MM/DD/YYYY) < '01/14/2013'

How can I get the most recent date in SQL?

I want to make a SQL query that gets todays date and the most recent date from a date column. So if I have three records in my database that have the following dates:
March 8, 2012
March 2, 2012
December 8, 2011
I want the SQL query to return all records for March 8, 2012 and March 2, 2012 (most recent date). How can I do this?
I can date today's date using:
CONVERT( varchar(100), DATEADD( DAY, 0, getdate() ), 111)
Thank You
Edit:
Thanks everyone. I just have one more question. I have created two views:
create view with top dates
CREATE VIEW topDates AS
select DISTINCT TOP 3 replace(CONVERT(VARCHAR(20),date,111),'-','/') AS dates from CSAResults.dbo.Details
create view dateTwo
select *
from (select ROW_NUMBER() over (order by dates desc) as srNo, dates
from topDates)
AS employee
WHERE srNo=2
And now I want to select * from my DB where a column is equal to the 'dates' column from the view 'dateTwo'
select buildNumber
from CSAResults.dbo.Details
where buildNumber LIKE '%Main '+ (SELECT dates FROM dateTwo) + '%'
But this returns nothing.
Thanks
You can do the following:
select date
from yourtable
where
(
date = Convert(varchar(10), getdate(), 101)
OR
date IN (SELECT Max(date)
FROM yourtable
WHERE date!= Convert(varchar(10), getdate(), 101))
)
Here is an example script that does what you are asking. It uses a sub-query to select all records with MAX on the date. You would just add an OR to also select items for the current date.
DECLARE #A TABLE
(
part_no VARCHAR(5),
rev CHAR,
on_hand TINYINT,
safety_stock TINYINT,
so_no VARCHAR(5),
so_date DATETIME
)
INSERT #A
SELECT '12345', 'A', 10, 15, 'S1234', '12/14/2009' UNION ALL
SELECT '12345', 'A', 10, 15, 'S1233', '10/01/2009' UNION ALL
SELECT '12345', 'A', 10, 15, 'S1232', '08/02/2009' UNION ALL
SELECT '12346', '', 5, 0, 'S1231', '08/01/2009' UNION ALL
SELECT '12347', '-', 0, 0, 'S1230', '10/20/2009' UNION ALL
SELECT '12347', '-', 0, 0, 'S1229', '07/15/2009'
SELECT * FROM #A AS A
WHERE so_date =
(
SELECT MAX(so_date)
FROM #A AS B
WHERE B.part_no = A.part_no AND B.Rev = A.Rev
)
SELECT *
INTO #TEMP
FROM
(
SELECT GETDATE() DATE_FIELD, 'Blah1...' OTHER_FIELDS
UNION SELECT GETDATE() DATE_FIELD, 'Blah2...' OTHER_FIELDS
UNION SELECT DATEADD(d,-1,GETDATE()) DATE_FIELD, 'Blah3...' OTHER_FIELDS
UNION SELECT DATEADD(d,-1,GETDATE()) DATE_FIELD, 'Blah4...' OTHER_FIELDS
UNION SELECT DATEADD(d,-3,GETDATE()) DATE_FIELD, 'Blah5...' OTHER_FIELDS
) A
SELECT * FROM #TEMP
SELECT * FROM
(
SELECT DATE_FIELD, OTHER_FIELDS,
DENSE_RANK() OVER (ORDER BY DATE_FIELD DESC) _RANK
FROM #TEMP
) A
WHERE A._RANK < 3
For your second question:
select buildNumber
from CSAResults.dbo.Details
inner join dateTwo
on buildNumber LIKE '%Main '+ dateTwo.dates + '%'