MS SQL Query min/max/average per day - sql-server

I have a query:
WITH cte AS(
SELECT T3.DateTime AS AADateTime,
(T3.In_Minbps/1000)/1000 AS MinReceiveMbps,
(T3.In_Maxbps/1000)/1000 AS MaxReceiveMbps,
(T3.In_Averagebps/1000)/1000 AS AvgReceiveMbps,
(T3.Out_Minbps/1000)/1000 AS MinTransmitMbps,
(T3.Out_Maxbps/1000)/1000 AS MaxTransmitMbps,
(T3.Out_Averagebps/1000)/1000 AS AvgTransmitMbps
FROM dbo.Nodes AS T1
INNER JOIN dbo.Interfaces AS T2 ON [T1].[NodeID] = [T2].[NodeID]
INNER JOIN InterfaceTraffic AS T3 ON [T2].[InterfaceID] = [T3].[InterfaceID]
WHERE [T1].[Caption] = 'cust-firewall01'
AND [T2].[InterfaceName] = 'reth0'
AND DateTime >= '2014-08-01 00:00:00' AND DateTime <= '2014-08-31 23:59:59'
)
SELECT MIN(AADateTime) AS AADateTime,
MIN(MinReceiveMbps) AS MinReceiveMbps,
MAX(MaxReceiveMbps) AS MaxReceiveMbps,
MIN(MinTransmitMbps) AS MinTransmitMbps,
MAX(MaxTransmitMbps) AS MaxTransmitMbps,
AVG(AvgTransmitMbps) AS AvgTransmitMbps,
AVG(AvgReceiveMbps) AS AvgReceiveMbps
FROM cte
The above query works however returns an min/max/average of all records, what I need to do is return min/max/average per day. example table data is:
Date, In_Minbps, In_Maxbps, In_Averagebps, Out_Minbps, Out_Maxbps, Out_Averagebps
2014-08-01 00:00:00, 403227.2, 3489988, 1986171, 6509198, 6.510824e+07, 33357.06
2014-08-01 01:00:00, 404039.1, 3626866, 2211984, 4491261, 6.61291e+07, 37061.19
there are basically 24 records per day I need this per day:
SELECT MIN(AADateTime) AS AADateTime,
MIN(MinReceiveMbps) AS MinReceiveMbps,
MAX(MaxReceiveMbps) AS MaxReceiveMbps,
MIN(MinTransmitMbps) AS MinTransmitMbps,
MAX(MaxTransmitMbps) AS MaxTransmitMbps,
AVG(AvgTransmitMbps) AS AvgTransmitMbps,
AVG(AvgReceiveMbps) AS AvgReceiveMbps
FROM cte

SELECT CAST(Datetimefield AS DATE) AS Date,
MIN(MinReceiveMbps) AS MinReceiveMbps,
MAX(MaxReceiveMbps) AS MaxReceiveMbps,
MIN(MinTransmitMbps) AS MinTransmitMbps,
MAX(MaxTransmitMbps) AS MaxTransmitMbps,
AVG(AvgTransmitMbps) AS AvgTransmitMbps,
AVG(AvgReceiveMbps) AS AvgReceiveMbps
FROM cte
GROUP BY CAST(Datetimefield AS DATE)
Its group by date your records.

Related

SQL Query Get Last record Group by multiple fields

Hi I have a table with following fields:
ALERTID POLY_CODE ALERT_DATETIME ALERT_TYPE
I need to query above table for records in the last 24 hour.
Then group by POLY_CODE and ALERT_TYPE and get the latest Alert_Level value ordered by ALERT_DATETIME
I can get up to this, but I need the AlertID of the resulting records.
Any suggestions what would be an efficient way of getting this ?
I have created an SQL in SQL Server. See below
SELECT POLY_CODE, ALERT_TYPE, X.ALERT_LEVEL AS LAST_ALERT_LEVEL
FROM
(SELECT * FROM TableA where ALERT_DATETIME >= GETDATE() -1) T1
OUTER APPLY (SELECT TOP 1 [ALERT_LEVEL]
FROM (SELECT * FROM TableA where ALERT_DATETIME >= GETDATE() -1) T2
WHERE T2.POLY_CODE = T1.POLY_CODE AND
T2.ALERT_TYPE = T1.ALERT_TYPE ORDER BY T2.[ALERT_DATETIME] DESC) X
GROUP BY POLY_CODE, ALERT_TYPE, X.[ALERT_LEVEL]
POLY_CODE ALERT_TYPE ALERT_LEVEL
04575 Elec 2
04737 Gas 3
06239 Elec 2
06552 Elec 2
06578 Elec 2
10320 Elec 2
select top 1 with ties *
from TableA
where ALERT_DATETIME >= GETDATE() -1
order by row_number() over (partition by POLY_CODE,ALERT_TYPE order by [ALERT_DATETIME] DESC)
The way this works is that for each group of POLY_CODE,ALERT_TYPE get their own row_number() starting from the most recent alert_datetime. Then, the with ties clause ensures that all rows(= all groups) with the row_number value of 1 get returned.
One way of doing it is creating a cte with the grouping that calculates the latesdatetime for each and then crosses it with the table to get the results. Just keep in mind that if there are more than one record with the same combination of poly_code, alert_type, alert_level and datetime they will all show.
WITH list AS (
SELECT ta.poly_code,ta.alert_type,MAX(ta.alert_datetime) AS LatestDatetime,
ta.alert_level
FROM dbo.TableA AS ta
WHERE ta.alert_datetime >= DATEADD(DAY,-1,GETDATE())
GROUP BY ta.poly_code, ta.alert_type,ta.alert_level
)
SELECT ta.*
FROM list AS l
INNER JOIN dbo.TableA AS ta ON ta.alert_level = l.alert_level AND ta.alert_type = l.alert_type AND ta.poly_code = l.poly_code AND ta.alert_datetime = l.LatestDatetime

How to get the transaction data with Date from First transaction date and Address from latest transaction Date if updated?

I am trying to rearrange the data with Date as First transaction/Shopping date and address from latest transaction. The Data consists of transaction of a single customer on various dates. Please help.
The Desired Out should be like:
Due to lack of table structure etc., here some "dummy" code. The idea is to first evaluate min and max date for each customer and then perform a join between the corresponding records:
WITH cte AS(
SELECT [Customer Code_Transaction]) AS CustomerCode
,min([Invoice Date_Transaction]) AS MinDate
,max([Invoice Date_Transaction]) AS MaxDate
FROM [yourtable...]
GROUP BY [Customer Code_Transaction]
)
SELECT t1.[Invoice Date_Transaction]
,t1.[Customer Code_Transaction]
,t1.[Customer Name_Transaction]
,t2.[Address_CustReport]
FROM [yourtable...] AS t1
JOIN cte AS c ON c.MinDate = t1.[Invoice Date_Transaction] AND c.CustomerCode = t1.[Customer Code_Transaction]
JOIN [yourtable...] AS t2 ON t2.[Customer Code_Transaction] = c.[Customer Code_Transaction] AND t2.[Invoice Date_Transaction] = c.MaxDate

SSRS:How to return count of events per day for Month

I have a table with the following information
ID,DateTime,EventType
1,6/5/2013 9:35:00,B
1,6/5/2013 9:35:24,A
2,6/5/2013 9:35:36,B
3,6/5/2013 9:36:11,D
2,6/5/2013 9:39:16,A
3,6/5/2013 9:40:48,B
4,7/5/2013 9:35:19,B
4,7/5/2013 9:35:33,A
5,7/5/2013 9:35:53,B
5,7/5/2013 9:36:06,D
6,7/5/2013 9:39:39,A
7,7/5/2013 9:40:28,B
8,8/5/2013 9:35:02,A
7,8/5/2013 9:35:08,A
8,8/5/2013 9:35:29,B
6,8/5/2013 9:36:39,B
I need to count how many times each day an event changed state as long as the time between states was less than 30 seconds over the time period.
Basically I am looking for the following result set
6/5/2013 | 1
7/5/2013 | 2
8/5/2013 | 1
I've tried several different types of queries, but nothing works. I am using SQL Server Reporting Services 2008.
declare #t table (ID int,[DateTime] datetime ,EventType varchar);
insert #t values
(1,'6/5/2013 9:35:00','B'),
(1,'6/5/2013 9:35:24','A'),
(2,'6/5/2013 9:35:36','B'),
(3,'6/5/2013 9:36:11','D'),
(2,'6/5/2013 9:39:16','A'),
(3,'6/5/2013 9:40:48','B'),
(4,'7/5/2013 9:35:19','B'),
(4,'7/5/2013 9:35:33','A'),
(5,'7/5/2013 9:35:53','B'),
(5,'7/5/2013 9:36:06','D'),
(6,'7/5/2013 9:39:39','A'),
(7,'7/5/2013 9:40:28','B'),
(8,'8/5/2013 9:35:02','A'),
(7,'8/5/2013 9:35:08','A'),
(8,'8/5/2013 9:35:29','B'),
(6,'8/5/2013 9:36:39','B');
--select * from #t order by ID, DateTime;
with cte as (
select *, cast([DateTime] as date) the_date, row_number() over (partition by ID order by DateTime) row_num
from #t
)
select c1.the_date, count(1)
from cte c1
join cte c2
on c2.ID = c1.ID
and c2.row_num = c1.row_num + 1
where datediff(S,c1.DateTime, c2.DateTime) < 30
group by c1.the_date
order by c1.the_date;
Try this:
select CONVERT(VARCHAR(10), a.DateTime, 103) [Date], count(a.ID) Count from Table a
inner join Table b on a.ID = b.ID
where DATEDIFF(second,a.DateTime,b.DateTime) between 1 and 29 and a.ID = b.ID
and Cast(a.DateTime as Date) = Cast(b.DateTime as date)
group by CONVERT(VARCHAR(10), a.DateTime, 103)

How execute/open multiple SQL statements in 1 go with ODBC / SQL-Server

What I'm basically trying to do is fire off multiple SQL statements in one go.
This works fine as long as they don't return results.
What I want to do is make a temporary table fill it and join it on my existing data:
CREATE TABLE #JaarMaandTable(jaarm int,maandm int)
INSERT INTO #JaarMaandTable (jaarm,maandm) VALUES (2013,9), (2013,10), (2013,11)
SELECT jaarm,maandm, kr.*
FROM #JaarMaandTable jm
LEFT JOIN (
SELECT DATEPART(Month, datum) as maand, DATEPART(Year, datum) as jaar ,count(*) as regels mytable
FROM agenda
WHERE datum >= '20130901'
AND datum <= '20131130'
GROUP BY DATEPART(Year, datum), DATEPART(Month, datum)
)kr ON jm.jaarm = kr.jaar AND jm.maandm = kr.maand ORDER BY jaarm, maandm
This is to make use of a temp table to split up results in months even when there's no data for those months.
It works fine in query analyser.
When I try to use "open" on this query, it tells me it doesn't return a cursor.
When I "execsql" it, it won't return results.
When I split it up, it immediately forgets the #temptable.
You can write the query using a with statement, to avoid the need for a temporary table:
with JaarMaandTable(jaarm int,maandm int) as (
select 2013, 9 union all
select 2013, 10 union all
select 2013, 11
)
SELECT jaarm,maandm, kr.*
FROM JaarMaandTable jm
LEFT JOIN (
SELECT DATEPART(Month, datum) as maand, DATEPART(Year, datum) as jaar ,count(*) as regels mytable
FROM agenda
WHERE datum >= '20130901'
AND datum <= '20131130'
GROUP BY DATEPART(Year, datum), DATEPART(Month, datum)
)kr ON jm.jaarm = kr.jaar AND jm.maandm = kr.maand ORDER BY jaarm, maandm

SQL Server T-SQL: Get a records set based on a priority value, startdate and enddate

I am working on an time attendance system. I have to following tables:
Schedule: Contains a Name nvarchar field and a Start and End DateTime fields.
Policy: Contains Start and End DateTime fields too.
PolicySchedule (Cross Table): Contains a Priority int field beside the foreign keys.
End datetime fields are nullable which indicates open periods.
The schedule of the greatest priority will be applied and activated within its time and the policy time.
I need to get a list of the applied schedules within each policy and their activation periods start and end time knowing that shedules may be intersected. Policies are not related here ..
Example:
Schedule_____________Start_________________________End
Schedule1____________01/01/2011 00:00______________04/01/2011 00:00
Schedule2____________04/01/2011 00:00______________11/01/2011 14:00
Schedule3____________11/01/2011 14:00______________02/15/2012 00:00
Schedule2____________02/15/2012 00:00______________01/01/2013 00:00
What is the most efficient way to get the requested result ?
If you have lots of policies and schedules (separately) but few schedules per policy, the most straightforward way would be quite efficient:
WITH dates (policyId, changeDate) AS
(
SELECT policyId, changeDate,
ROW_NUMBER() OVER (PARTITION BY policyId ORDER BY changeDate) AS rn
FROM (
SELECT policyId, startDate AS changeDate
FROM policySchedule ps
JOIN schedule s
ON s.id = ps.scheduleId
UNION
SELECT policyId, endDate AS changeDate
FROM policySchedule ps
JOIN schedule s
ON s.id = ps.scheduleId
) q
),
ranges (startDate, endDate)AS
(
SELECT d1.policyId,
d1.changeDate,
d2.changeDate
FROM dates d1
JOIN dates d2
ON d2.policyId = d1.policyId
AND d2.rn = d1.rn + 1
)
SELECT *
FROM policy p
JOIN ranges r
ON r.policyId = p.id
CROSS APPLY
(
SELECT TOP 1 s.*
FROM policySchedules ps
JOIN schedule s
ON ps.policyId = p.id
AND s.id = ps.scheduleId
WHERE ps.startDate BETWEEN r.startDate AND r.endDate
AND ps.endDate BETWEEN r.startDate AND r.endDate
ORDER BY
ps.Priority DESC
)
Assuming you're using SQL Server 2005 or later, you can use an outer apply to look up the policy with the highest priority:
select *
from Schedule s
outer apply
(
select top 1 *
from PolicySchedule ps
join Policy p
on p.id = ps.policyid
where s.StartTime <= p.EndTime
and p.StartTime <= s.EndTime
order by
ps.priority desc
) pol
If there are time periods that have to overlap, you can add a where clause in the outer apply.

Resources