SQL Select Highest Surge of Activity in period of time - sql-server

I am working on a database dealing with information regarding red-light violations from the beginning of the year until present-day.
The table I'm working with is Violations[TicketID, CameraID, DateOfViolation]
I want to find a CameraID with the most amount of tickets serviced (which amounts to a new entry in Violations) in, say, the last 7 days. If there is no activity in the last 7 days, I want null to be returned (i.e. don't open the range to be the last 14 days).
What is the command for this? I'm not sure how to even begin adding constraint for past 7 days. I am connecting to a Microsoft SQL Server.

select top 1 CameraID
from violations
where DateOfViolation >= dateadd(day, -7, getdate())
group by CameraID
order by count(*) desc

Related

Count by days, with all days

I need to count records by days, even if in the day were no records.
Count by days, sure, easy.
But how i can make it to print information, that 'in day 2018-01-10 was 0 records)
Should I use connect by level? Please, any help would be good. Can't use plsql, just oracle sql
First you generate every date that you want in an inline view. I chose every date for the current year because you didn't specify. Then you left outer join on date using whichever date field you have in that table. If you count on a non-null field from the source table then it will count 0 rows on days where there is no join.
select Dates.r, count(tablename.id)
from (select trunc(sysdate,'YYYY') + level - 1 R
from dual
connect by level <= trunc(add_months(sysdate,12),'YYYY') - trunc(sysdate,'YYYY')) Dates
left join tablename
on trunc(tablename.datefield) = Dates.r
group by Dates.r

Selecting Different rows if the values of one column are equal

I am trying to write a SQL query that selects the top 4 from a random query so I can do quality checks on the certain cases. Each case has an account number tied to a client. The problem is that each case has a unique number but may have the same account number.
What I am looking to do is if the account number is the same on two cases to have the SQL select a new row with a different account number.
Select Top 4
Account,
CaseNum
From dbo.tblRequest
Where LoggedDate Between GetDate() - 7 and GetDate() - 1
Order By NewId();
The Results will display 4 accounts but at times it is possible that the same account is displayed twice. As stated I want to only display distinct accounts for a 7 day period.
I have tried the distinct key word and it still displays the accounts twice in some queries results.
Try following statement. using row_number to get only on line for same accountNumber.
SELECT * FROM (
Select
Account,
CaseNum,
ROW_NUMBER()OVER(PARTITION BY Account ORDER BY GETDATE()) AS rn
From dbo.tblRequest
Where LoggedDate Between GetDate() - 7 and GetDate() - 1
) AS t WHERE t.rn=1
Order By
NewId()

SQL Server Amount "Open" At Each Month End

I need to create a query that will sum the Amount of Open Accounts Receivable for each month.
Each record in my table has Amount,Posting Date, and Closed at Date. So for example, one record might be: Amount : 5000, Posting Date : 1/1/15, Closed at Date : 3/5/15. So for this record, the 5000 would need to be added to my January Open AR calculation because it is open as of 1/31/15, added to my February Open AR calculation because it is open as of 2/28/15, but excluded from my March Open AR calculation because it is closed as of 3/31/15.
I have managed to create a query that will work for an individual month, given a single inputted month-end date, i.e. 1/31/15 or 2/28/15, etc..., which goes into the WHERE clause.
SELECT SUM(Amount), threemonthavg, SUM(Amount)/threemonthavg AS DSO
FROM tbl1
WHERE PostDate <= #enddate AND ClosedDate > #enddate
Am I on the right track to expand this out to include each month in one query or would I be better off taking what I have, and creating a stored procedure to run this query for each month and union the results together?

Select most recent rows based on a DateTime field within 5 mins of current time

In a SQL Server table, I have a DateTime field and every time I have a login failure for an external web service I write the current DateTime to the table.
I currently have code that parses through the returns and determines if there are > 2 failures within 5 mins. If so I have a flag to turn off calling of the web service. I am curious if there is a way I can just use sql to return the number of rows that are within 5 mins from the current time?
This will return all records that are less than five minutes old:
SELECT [Columns]
FROM [YourTable]
WHERE [DateTimeField] >= dateadd(minute, -5, getdate())
You can get more information on DATEADD here .
You can try this
SELECT COUNT(*)
FROM MyTable
WHERE MyDateTimeField > DATEADD(mm, -5, GETDATE())

SQL Server Retrieving Recurring Appointments By Date

I'm working on a system to store appointments and recurring appointments. My schema looks like this
Appointment
-----------
ID
Start
End
Title
RecurringType
RecurringEnd
RecurringTypes
---------------
Id
Name
I've keeped the Recurring Types simple and only support
Week Days,
Weekly,
4 Weekly,
52 Weekly
If RecurringType is null then that appointment does not recur, RecurringEnd is also nullable and if its null but RecurringType is a value then it will recur indefinatly. I'm trying to write a stored procedure to return all appointments and their dates for a given date range.
I've got the stored procedure working for non recurring meetings but am struggling to work out the best way to return the recurrences this is what I have so far
ALTER PROCEDURE GetAppointments
(
#StartDate DATETIME,
#EndDate DATETIME
)
AS
SELECT
appointment.id,
appointment.title,
appointment.recurringType,
appointment.recurringEnd,
appointment.start,
appointment.[end]
FROM
mrm_booking
WHERE
(
Start >= #StartDate AND
[End] <= #EndDate
)
I now need to add in the where clauses to also pick up the recurrences and alter what is returned in the select to return the Start and End Dates for normal meetings and the calculated start/end dates for the recurrences.
Any pointers on the best way to handle this would be great. I'm using SQL Server 2005
you need to store the recurring dates as each individual row in the schedule. that is, you need to expand the recurring dates on the initial save. Without doing this it is impossible to (or extremely difficult) to expand them on the fly when you need to see them, check for conflicts, etc. this will make all appointments work the same, since they will all actually have a row in the table to load, etc. I would suggest that when a user specifies their recurring date, you make them pick an actual number of recurring occurrences. When you go to save that recurring appointment, expand them all out as individual rows in the table. You could use a FK to a parent appointment row and link them like a linked list:
Appointment
-----------
ID
Start
End
Title
RecurringParentID FK to ID
sample data:
ID .... RecurringParentID
1 .... null
2 .... 1
3 .... 2
4 .... 3
5 .... 4
if in the middle of the recurring appointments schedule run, say ID=3, they decide to cancel them, you can follow the chain and delete the remaining ID=3,4,5.
as for expanding the dates, you could use a CTE, numbers table, while loop, etc. if you need help doing that, just ask. the key is to save them as regular rows in the table so you don't need to expand them on the fly every time you need to display or evaluate them.
I ended up doing this by creating a temp table of everyday between the start and end date along with their respective day of the week. I limited the recurrence intervals to weekdays and a set amount of weeks and added where clauses like this
--Check Week Days Reoccurrence
(
mrm_booking.repeat_type_id = 1 AND
#ValidWeeklyDayOfWeeks.dow IN (1,2,3,4,5)
) OR
--Check Weekly Reoccurrence
(
mrm_booking.repeat_type_id = 2 AND
DATEPART(WEEKDAY, mrm_booking.start_date) = #ValidWeeklyDayOfWeeks.dow
) OR
--Check 4 Weekly Reoccurences
(
mrm_booking.repeat_type_id = 3 AND
DATEDIFF(d,#ValidWeeklyDayOfWeeks.[Date],mrm_booking.start_date) % (7*4) = 0
) OR
--Check 52 Weekly Reoccurences
(
mrm_booking.repeat_type_id = 4 AND
DATEDIFF(d,#ValidWeeklyDayOfWeeks.[Date],mrm_booking.start_date) % (7*52) = 0
)
In case your interested I built up a table of the days between the start and end date using this
INSERT INTO #ValidWeeklyDayOfWeeks
--Get Valid Reoccurence Dates For Week Day Reoccurences
SELECT
DATEADD(d, offset - 1, #StartDate) AS [Date],
DATEPART(WEEKDAY,DATEADD(d, offset - 1, #StartDate)) AS Dow
FROM
(
SELECT ROW_NUMBER() OVER(ORDER BY s1.id) AS offset
FROM syscolumns s1, syscolumns s2
) a WHERE offset <= DATEDIFF(d, #StartDate, DATEADD(d,1,#EndDate))
Its not very elegant and probably very specific to my needs but it does the job I needed it to do.

Resources