How to choose the 12 prior weeks in SQL - sql

It had a lot of row with NULL value which I deleted using the following query:
/* DELETE EVERY ROW EXCEPT THE ROW WE NEED */
DELETE FROM [Database].[dbo].[Table]
WHERE
([Week Of*] IS NULL)
How do I write a query which will get the prior 12 weeks from the current rolling week and insert the [F4] value into a table

SELECT f4
FROM yourtable
WHERE DATEADD(week, -12, [Week Of*]) >= 12

I ended up using the following which gave me the last 12 weeks (how ever I have to use 14 to get the 12 weeks. Still trying to figure out why:
SELECT CONVERT(VARCHAR(10),[Week Of*],110) AS [Date], [F18] AS [TOTALS] FROM [db].[DBO].[table] WHERE CONVERT(VARCHAR(10),[Week Of*],110) >= DATEADD(week, -14, GETDATE())

Related

forever loop sql

I am trying to find all staff not logged on in the last 6 months so I have this code. It seems to be looping forever but I'm not sure why
--select all staff not logged on in the last 6 months
SELECT
[fkStaffId],
[dteLogon]
FROM
[dbo].[tbl_Staff_Logon]
WHERE
[fkStaffId]
NOT IN
(--select all staff logged on in the last 6 months
SELECT DISTINCT
[fkStaffId]
FROM
[dbo].[tbl_Staff_Logon]
WHERE
[dteLogon] > DATEADD(MONTH, -6, GETDATE()) --this is a list of each staffID
--logged on in the last 6 months
)
ORDER BY [dteLogon] DESC
anybody got any idea why?
if i just execute
SELECT DISTINCT
[fkStaffId]
FROM
[dbo].[tbl_Staff_Logon]
WHERE
[dteLogon] > DATEADD(MONTH, -6, GETDATE())
on it's own, I get a sensible sized list of 309 lines which is about the number I'm expecting, however, the last time I tried to run the entire code, it was still executing after 25 minutes!!
I'd do a GROUP BY, and use HAVING to only return users who have not logged in recently:
SELECT
[fkStaffId], MAX([dteLogon])
FROM
[dbo].[tbl_Staff_Logon]
GROUP BY [fkStaffId]
HAVING MAX([dteLogon]) < DATEADD(MONTH, -6, GETDATE())

How to i find records in the last month that do not have a "Date created" column

Im trying to find records that have not had notes created during the last 1 month. The table only registers when a note is created.
I am trying to find NULL values, but that would not be the correct logic
SELECT *
FROM vpersonnotesalldata AS pn
WHERE pn.flddatecreated > '20190501'
AND pn.fldnotedatecreated < '20190530'
If you want records which don't have a note in last 30 days, try this:
select p.* from person p where personid not in (
select personid from Note where dateCreated < dateadd(d, -30, GetDate())
)
Obviously use your actual table names in your sql
Try this with example last month
SELECT *
FROM vpersonnotesalldata AS pn
WHERE pn.NoteColumnHERE IS NULL
AND pn.CreateDateColumnHERE
BETWEEN '01.05.2019'
AND '31.05.2019'
It picks all pn.NoteColumnHERE which are NULL in the Span of pn.CreateDateColumnHERE BETWEEN 01.05. and 31.05.
I hope the Date Input is correct for your SQL Version. In Microsoft SQL it is working!
The performance will be much better if you use EXISTS / NOT EXISTS instead of IN / NOT IN
SELECT *
FROM Client C
WHERE NOT EXISTS (
SELECT 1
FROM vpersonnotesalldata
WHERE
fldClientNumber = C.fldClientNumber
AND fldnotedatecreated BETWEEN
DATEADD(MONTH, DATEDIFF(MONTH, 0, GETDATE())-1, 0) --First day of previous month
AND DATEADD(MONTH, DATEDIFF(MONTH, -1, GETDATE())-1, -1) --Last Day of previous month
)

SQL Week over Week query for given timeframe

I have a table that is used for support tickets. I am trying to create a query that shows a week over week breakdown (how many tickets were created) for the last 8 weeks.
I have a calendar table created already and I am trying to make use of this to create the query.
Example:
SELECT *
FROM dbo.Calendar
WHERE calendar_DT >= DATEADD(week, -8, GETUTCDATE() -1)
AND calendar_DT <= GETUTCDATE()
ORDER BY calendar_DT ASC
Here I have a basic query that gives me all of the dates within the last 8 weeks. From here, I am trying to group this data by week so that I have a weekStart, weekEnd and then a count of records created which I will join another table for.
I attempted to do this without a calendar table but it seems that if records didn't exist for a specific week then theres gaps in the results instead of a 0.
This was my original attempt. Its close to what I want for the end result. However, I am not sure where the null is coming from and its missing a 2 weeks of data where no requests were created during this time.
SELECT DATEADD(week, DATEDIFF(week, 0, createdDate), 0) [From],
DATEADD(week, DATEDIFF(week, 0, createdDate), 0) + 6 [To],
COUNT(DISTINCT reqID) newRequests
FROM dbo.support_tickets
WHERE createdDate >= DATEADD(week, -8, GETUTCDATE())
AND tool = 244
GROUP BY DATEDIFF(week, 0, createdDate) WITH ROLLUP
ORDER BY DATEDIFF(week, 0, createdDate)
Desired result looks like the image above, a total count of records created for each of the last 8 weeks.
Do I need to continue with the use of the calendar table or can it be done without it and still show the to/from even if theres no results for that week?
The NULL row is the result of your GROUP BY...WITH ROLLUP. That's the rollup. The newRequests value of 7 is the total of your other records.
If you want dates to be listed that aren't in your table, you'll need to get them from somewhere else, which is just what a calendar table is for. So you're actually in pretty good shape once you add that join.

Need to find out last 15 days record (each day which record are last inserted in my table )

Need Help
Lets say--I have a staging table, everyday record are inserted, there is column is T_CREATED, This column has date (ddmmyyy hh24miss) example “12/16/2014 11:47:14 AM”
My scenario was, I need to find out when is last record last 15 days. Which means each day(in 24 hr) which record are last inserted
Can I get suggestion here?
I know I have to use MAX(T_CREATED) but could not figure it out.
Thanks
Sohel
I am not sure about the syntax in Oracle, this code will return the latest T_CREATED for each day.
-- SQL Server
SELECT MAX(obj_ID) AS MaxID, CONVERT(DATE, T_CREATED) AS [Date]
FROM source_tbl
WHERE CONVERT(DATE, T_CREATED) > CONVERT(DATE, DATEADD(DAY, -15, GETDATE()))
GROUP BY CONVERT(DATE, T_CREATED)
ORDER BY CONVERT(DATE, T_CREATED) DESC
-- Oracle
SELECT MAX(T_CREATED) AS MaxID, TRUNC(T_CREATED) AS [Date]
FROM source_tbl
WHERE TRUNC(T_CREATED) > TRUNC(SYSDATE - 15)
GROUP BY TRUNC(T_CREATED)
ORDER BY TRUNC(T_CREATED) DESC

Query to check number of records created in a month.

My table creates a new record with timestamp daily when an integration is successful. I am trying to create a query that would check (preferably automated) the number of days in a month vs number of records in the table within a time frame.
For example, January has 31 days, so i would like to know how many days in january my process was not successful. If the number of records is less than 31, than i know the job failed 31 - x times.
I tried the following but was not getting very far:
SELECT COUNT (DISTINCT CompleteDate)
FROM table
WHERE CompleteDate BETWEEN '01/01/2015' AND '01/31/2015'
Every 7 days the system executes the job twice, so i get two records on the same day, but i am trying to determine the number of days that nothing happened (failures), so i assume some truncation of the date field is needed?!
One way to do this is to use a calendar/date table as the main source of dates in the range and left join with that and count the number of null values.
In absence of a proper date table you can generate a range of dates using a number sequence like the one found in the master..spt_values table:
select count(*) failed
from (
select dateadd(day, number, '2015-01-01') date
from master..spt_values where type='P' and number < 365
) a
left join your_table b on a.date = b.CompleteDate
where b.CompleteDate is null
and a.date BETWEEN '01/01/2015' AND '01/31/2015'
Sample SQL Fiddle (with count grouped by month)
Assuming you have an Integers table*. This query will pull all dates where no record is found in the target table:
declare #StartDate datetime = '01/01/2013',
#EndDate datetime = '12/31/2013'
;with d as (
select *, date = dateadd(d, i - 1 , #StartDate)
from dbo.Integers
where i <= datediff(d, #StartDate, #EndDate) + 1
)
select d.date
from d
where not exists (
select 1 from <target> t
where DATEADD(dd, DATEDIFF(dd, 0, t.<timestamp>), 0) = DATEADD(dd, DATEDIFF(dd, 0, d.date), 0)
)
Between is not safe here
SELECT 31 - count(distinct(convert(date, CompleteDate)))
FROM table
WHERE CompleteDate >= '01/01/2015' AND CompleteDate < '02/01/2015'
You can use the following query:
SELECT DATEDIFF(day, t.d, dateadd(month, 1, t.d)) - COUNT(DISTINCT CompleteDate)
FROM mytable
CROSS APPLY (SELECT CAST(YEAR(CompleteDate) AS VARCHAR(4)) +
RIGHT('0' + CAST(MONTH(CompleteDate) AS VARCHAR(2)), 2) +
'01') t(d)
GROUP BY t.d
SQL Fiddle Demo
Explanation:
The value CROSS APPLY-ied, i.e. t.d, is the ANSI string of the first day of the month of CompleteDate, e.g. '20150101' for 12/01/2015, or 18/01/2015.
DATEDIFF uses the above mentioned value, i.e. t.d, in order to calculate the number of days of the month that CompleteDate belongs to.
GROUP BY essentially groups by (Year, Month), hence COUNT(DISTINCT CompleteDate) returns the number of distinct records per month.
The values returned by the query are the differences of [2] - 1, i.e. the number of failures per month, for each (Year, Month) of your initial data.
If you want to query a specific Year, Month then just simply add a WHERE clause to the above:
WHERE YEAR(CompleteDate) = 2015 AND MONTH(CompleteDate) = 1