finding records relative to today - sql

I have a table named dbstorage which has columns like year and weekno.
I need to select the year and weekno which is less than current year and current week.
I used:
select * from dbstorage where year<=2011 and weekno<=13.
But it is not giving the correct data like if I have a value
year:2010 and weekno:25 means, the query is not selecting this record.
How can this be done?

You can split it out into two cases and use or
SELECT * /*<-- But don't use * List the columns explicitly*/
FROM dbstorage
WHERE ( year = 2011
AND weekno <= 13 )
OR year < 2011
Edit
But And logic may well be more efficient
SELECT *
FROM dbstorage
WHERE ( year <= 2011 )
AND ( year < 2011
OR weekno <= 13 )

you have to split up the search into multiple parts:
select * from dbstorage
where
(year = 2011 and weekno <= 13) -- will catch all weeks in 2011 PRIOR to this one
or (year < 2011) -- will catch all weeks in 2010 and earlier

For SQL Server you can also do:
SELECT *
FROM dbstorage
WHERE (year = DATEPART(yyyy, GETDATE())
AND weekno <= DATEPART(ww, GETDATE()))
OR year < DATEPART(yyyy, GETDATE())

Related

Query to select between two dates without year

I am trying to update certain fields for employees whose date of joining falls in between 10 Jun and 31 Dec, irrespective of the year. I am trying using 'Between' Operator but it requires year to be included in the dates. Is there a way to generalise it in order to consider Day and Month excluding the Year?
Use the DatePart function - replace thedate with your column, and thetable with the column.
Something like this:
select datepart(MONTH, thedate), datepart(DAY, thedate),*
from thetable
where datepart(MONTH, thedate) between 6 and 12
and datepart(DAY, thedate) between 10 and 31
You may try this:
WITH Emp AS (
SELECT *, DATEPART(MONTH, JoinDate) AS MonthJoin, DATEPART(DAY, JoinDate) AS DayJoin
FROM Employees)
SELECT *
FROM Emp
WHERE (MonthJoin > 1 AND MonthJoin < 12)
OR (MonthJoin = 1 AND DayJoin >= 10)
OR (MonthJoin = 12 AND DayJoin <= 31)
Where Employees is your table and JoinDate is your date of joining in this table

Sum of numbers from previous year month until this years month in SQL

Being a beginner, I'm having a hard time coding this particular scenario in SQL Server 2008
As you can see,
The SUM column for July 2017 for example is equal to the following:
August to Dec 2016 + Jan to July 2017 = 4625
Similarly, the SUM column for August 2017 is equal to the following:
Sep to Dec 2016 + Jan to August 2017 = 4625
How can I automate this from month to month?
I appreciate any help I can get. Trying to code this in SQL Server 2008
Using this methodology to find the first day of the current month:
select dateadd(month, datediff(month, 0, getdate()), 0)
We can expan on it to get the first day, of the next month, a year ago... i.e. 11 months ago.
select dateadd(month, datediff(month, 0, dateadd(month,-11,getdate())), 0)
Then, we just need to use it in a where clause to limit your data...
declare #startDate = (select dateadd(month, datediff(month, 0, dateadd(month,-11,getdate())), 0))
declare #endDate = getdate()
select sum(someColumn)
from someTable
where dateColumn between #startDate and #endDate
Since you didn't provide your actual data set, just some pivoted data, I'm not sure of your column and table names
This sounds like you want window functions. Assuming your data is already summarized by month:
select t.*,
sum(numbers) over (order by yyyymm rows between 11 preceding and current row) as prev_12_sum
from t;
If the data is not already summarized, you can put this in a group by as well:
select year(date), month(date),
sum(sum(numbers)) over (order by year(date), month(date) rows between 11 preceding and current row) as prev_12_sum
from t
group by year(date), month(date)
order by min(date);

SQL Server query get count of X on 15th of each month

I would like to create an SQL query that gets the count of employees that were employed as of the 15th of each month of the last 5 years.
This query gets me a single month:
SELECT
SUM(X.CountOfEmployees)
FROM (SELECT
COUNT(CNCEmployeeID) AS CountOfEmployees
FROM dbo.CNCEmployees
GROUP BY CNCEmployeeStartDate,
CNCEmployeeDateLeft
HAVING (CNCEmployeeStartDate < CONVERT(datetime, '2016-07-15 00:00:00', 102))
AND ((CNCEmployeeDateLeft > CONVERT(datetime, '2016-07-15 00:00:00', 102))
OR (CNCEmployeeDateLeft IS NULL))) AS X
What I am looking for would output:
Jan 2016 - 32
Feb 2016 - 33
Mar 2016 - 33
etc. for each month that we have data.
I know how to create a Query and at least make it quick to change the dates by hand by adding a variable and changing that over and over (in fact I will probably do that to get the report done today for the last 12 months). I believe that there is a better way to do this in one step without the need to manually go through each month.
One method generates for the 60 months and use that in the join:
with dates as (
select cast(dateadd(day, 16 - day(getdate()), getdate()) as date) as thedate, 1 as num
union all
select dateadd(month, -1, thedate), num + 1
from dates
where num <= 60
)
select d.thedate, count(e.CNCEmployeeStartDate)
from dates d left join
dbo.CNCEmployees e
on e.CNCEmployeeStartDate <= d.thedate and
(e.CNCEmployeeDateLeft >= d.thedate or e.CNCEmployeeDateLeft is null)
group by d.thedate;
This is not the most efficient method, but if you have a few hundred or thousand employees it should be fine in terms of performance.

How to group daily data on weekly basis using sql

I am trying to group the number of hours that employees worked for the last 4 weeks but I want to group them on a weekly basis. For example:
WEEK HOURS
Feb 24 to March 2 55
March 3 to March 9 40
March 10 to March 16 48
March 17 to March 23 37
This is what I have so far, please help. thanks
SET DATEFIRST 1
SELECT CAST(MIN( [DT]) AS VARCHAR(20))+' TO '+CAST (MAX([DT]) AS VARCHAR(20)) AS DATE,
SUM(HOURS) AS NUM_HRS
FROM MyTable
GROUP BY DATEPART(WEEK,[DT])
HAVING COUNT(DISTINCT[DT])=7
Create a Calendar auxilliary table, with Year, Month, Week, Date columns (you can also add holidays and other interesting stuff to it, it has many potential uses) and populate it for the period of interest.
After that, it's as easy as this:
SELECT sum(hours), cast(min(date) as varchar), cast(max(date) as varchar)
FROM Calendar c
LEFT OUTER JOIN MyTable h on h.Date = c.date
GROUP BY year, week
ORDER BY year, week
SET DATEFIRST 1
SELECT DATEPART(WEEK,DT) AS WEEK,
SUM(HOURS) AS NUM_HRS
FROM MyTable
WHERE DT >= DATEADD(WEEK, -4, GetDate()),
GROUP BY DATEPART(WEEK,[DT])
Try something like
SELECT
DATEADD(DD,
CONVERT(INT, (DATEDIFF(DD, '1/1/1900', t.DT)/7)) * 7,
'1/1/1900') [WeekBeginDate],
DATEADD(DD,
(CONVERT(INT, (DATEDIFF(DD, '1/1/1900', t.DT)/7)) * 7) + 6,
'1/1/1900') [WeekEndDate],
SUM(HOURS) AS NUM_HRS
FROM MyTable t
GROUP BY CONVERT(INT, DATEDIFF(DD, '1/1/1900', t.DT)/7)
Though this is the brute force trick, I think in your case it will work.
EDIT : Modified the query a little bit, the error was caused because of the order in which DATEDIFF calculates the difference.
Also here is a SQL FIDDLE with a working example.
EDIT 2 : Updated the Fiddle with the Date Format. To customize the date format, this article would help.

Select data for last X month from table with year and month separated in different coloumns

on my SQL Server I have a table with a lot of data. There are two columns for year (smallint) and month (tinyint).
What is the best and most performed way to separate data for the last X month.
I have declared variables
#YearFrom
#YearTo
#MonthFrom
#MonthTo
with correct values. Now I have realised that my WHERE statement doesn't work as expected:
WHERE (year >= #yearfrom AND month >= #monthfrom)
AND (year <= #yearto AND month <= #monthto)
Because when selecting the data from the last 12 month, my variables are
#YearFrom = 2012
#YearTo = 2013
#MonthFrom = 9
#MonthTo = 9
and the SELECT would just give me data from 09 2012/2013
WHERE (year >= 2012 AND month >= 9)
AND (year <= 2013 AND month <= 9)
So, actually there are two possiblities to solve the problem:
First with variable X last month #lastMonth = 12
or with the 4 helper varibales I have declared (yearfrom, yearto, monthfrom, monthto).
Any suggestion how to solve this problem?!?!?
Thanks for every reply...
WHERE (year = #yearfrom AND month >= #monthfrom or year > #yearfrom)
AND (year = #yearto AND month <= #monthto or year < #yearto)