Get max min per group in sequence
I have a list like this below with desired result, please help.
The X are GPS cordinates, the time is the GPS times
X time
A 5
B 6
B 7
C 8
C 9
A 10
B 11
The result must be:
X min max
A 5 5
B 6 7
C 8 9
A 10 10
B 11 11
Here is a slightly diff solution, but you need SS 2012 or greater.
The idea is expressed in each CTE.
- Identify each new gps coordinate in time sequence per each car (new_gps).
- Count how many new_gps you have for each row in specific partition and windows frame (grp_helper).
- Aggregate to find min / max for each group (car, x, grp_helper).
- Bring next minTime
- APPLY to split the rows waiting and then moving
SET NOCOUNT ON;
USE tempdb;
GO
Create table #test (Car int, X Char(1), [Time] int)
INSERT INTO #test
VALUES
( 11, 'A', 5 ),
( 11, 'B', 6 ),
( 11, 'B', 7 ),
( 11, 'B', 8 ),
( 11, 'C', 9 ),
( 11, 'C', 10 ),
( 11, 'C', 11 ),
( 11, 'A', 12 ),
( 11, 'B', 13 );
-- ( 12, 'A', 15 ),
-- ( 12, 'B', 16 ),
-- ( 12, 'B', 17 ),
-- ( 12, 'B', 18 );
WITH C1 AS (
SELECT
Car,
X,
[Time],
CASE
WHEN X = LAG(X, 1, NULL) OVER(PARTITION BY Car ORDER BY [Time]) THEN 0 ELSE 1
END AS new_gps
FROM
#test
, C2 AS (
SELECT
Car,
X,
[Time],
SUM(new_gps) OVER(
PARTITION BY Car
ORDER BY [Time]
ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW
) AS grp_helper
FROM
C1
Agg AS (
SELECT
Car,
X,
MIN([Time]) AS minTime,
MAX([Time]) AS maxTime,
COUNT(*) AS cnt
FROM
C2
GROUP BY
Car,
X,
grp_helper
, C3 AS (
SELECT
Car,
X,
minTime,
maxTime,
cnt,
LEAD(minTime, 1, maxTime) OVER(PARTITION BY Car ORDER BY minTime) AS nxt_minTime
FROM
Agg
SELECT
T.Car,
T.X,
T.minTime,
T.maxTime,
T.moving
FROM
C3
CROSS APPLY
SELECT C3.Car, C3.X, C3.minTime, C3.maxTime, 1 AS moving
WHERE cnt = 1
UNION ALL
SELECT C3.Car, C3.X, C3.minTime, C3.maxTime, 0 AS moving
WHERE cnt > 1
UNION ALL
SELECT C3.Car, C3.X, C3.maxTime, C3.nxt_minTime, 1 AS moving
WHERE cnt > 1
) AS T
ORDER BY
T.Car,
T.minTime;
GO
DROP TABLE #test;
GO
AMB
Some guidelines for posting questions...
AYÚDANOS A AYUDARTE, guía básica de consejos para formular preguntas
Similar Messages
-
How can I get max, min & average (hours with minutes) of fast 30 days data
Table name:
run_log
TYPE VARCHAR2(10),
SUBTYPE VARCHAR2(10),
PROGRAM VARCHAR2(100),
STATUS VARCHAR2(20),
START_TIME DATE,
END_TIME DATE
How can I get max, min & average (hours with minutes) of fast 30 days data ?Hi,
you have to use analytical functions:
SELECT start_day,
round(AVG(daily_avg)
over(ORDER BY start_day ASC RANGE BETWEEN INTERVAL '30' DAY preceding AND INTERVAL '0' DAY following)) AS moving_avg,
round(MAX(daily_max)
over(ORDER BY start_day ASC RANGE BETWEEN INTERVAL '30' DAY preceding AND INTERVAL '0' DAY following)) AS moving_max,
round(MIN(daily_min)
over(ORDER BY start_day ASC RANGE BETWEEN INTERVAL '30' DAY preceding AND INTERVAL '0' DAY following)) AS moving_min
FROM (SELECT trunc(t.start_time) start_day,
AVG((t.end_time - t.start_time) * 24 * 60 * 60) AS daily_avg,
MAX((t.end_time - t.start_time) * 24 * 60 * 60) AS daily_max,
MIN((t.end_time - t.start_time) * 24 * 60 * 60) AS daily_min
FROM run_log
GROUP BY trunc(t.start_time)) t
ORDER BY 1 DESCAnalytical functions are described in the Oracle doc "Data Warehousing Guide".
Regards,
Carsten. -
How do you create a max/min for a series of input in labview 2010
with labview is there a way to get max/min values from a series of inputs? I want it to graph the data and keep track of what the highest and lowest values were. I am using Labview 2010
While you don't really define what you mean by a "Series of inputs", maybe Array Min&Max PrByPt might be of interest.
(For better help, attach a simplified VI that shows typical data.)
LabVIEW Champion . Do more with less code and in less time . -
SSAS Tabular DAX- Need to get MAX value of the MIN (top)hierarchy level row
EDIT:
I got closer to resolving the issue using MAX.
However, If I remove the department hierarchy and just place on the MAX measure I get the single largest value out of all departments.
It would be ideal if the measure could still SUM the "top level" values across everything in the system if the hierarchy is not placed on the rows grouping.
So it returns the largest value for a given department, but if the department hierarchy isn't present I need it to return a SUM of all the level 1 values for all departments...
Basically return MAX value from the MIN L1ID's DeptLevel value, but I can't seem to construct that DAX query. So if DepartmentID hierarchy is on display it gets MAX per row, but if that is removed it dips into MAX GoalValue for each L1ID grouping with
the MIN DeptLevel.
/EDIT
I have a rather odd data table I'm bringing into a SSAS Tabular model.
Instead of having all data at each child level and then it adding up to a grand total in the parent, it has a grand total predefined at each child level.
I just need this tool to display the raw data if at all possible instead of trying to aggregate everything. Filter on active level, ignore child levels.
Is there a way to do that?
Example:
SalesGoalsByDepartmentLevel:
Level1 (top level) = 5,000
Level2( lower level) = 0
Level3(lower still) = 500
Level 4(lowest) = 4,250
So note that adding up all the child levels is still $250 shy of the top 5,000.
IT is just an odd business rule, basically each level is expected to meet that goal or exceed it, the top level goal is 5,000 but management doesn't care where that last 250 comes from, they do are that each defined level is met.
These levels are in a hierarchy so if I view the top level of the hierarchy it adds up to 4250+500+5000=9750 when I just want to see 5,000 at the top level and the details when they drill down.
I added a filter to just filter to the top level, but then when I drill down of course those lower levels are blank.
Is there a way to filter on the current displayed level without aggregating all child levels?
Thanks!You might want to take a look at the Parent-Child Hierarchies pattern here:
http://www.daxpatterns.com/parent-child-hierarchies/
You might write DAX code to check what is the "current" level (see BrowseDepth measure in the sample file you can download) and depending on its level, se the filter to blank to all the levels below, so you don't aggregate "children".
Just an idea, I'm not sure if it corresponds to your requirement and I don't have time to make more tests.
I hope it will be helpful.
Marco Russo (Blog,
Twitter,
LinkedIn) - sqlbi.com:
Articles, Videos,
Tools, Consultancy,
Training
Format with DAX Formatter and design with
DAX Patterns. Learn
Power Pivot and SSAS Tabular. -
How to Get the min,max and original values in a single query
Hi,
I have a task where in i have to the min , max and the original values of a data set .
I have the data like below and i want the target as well as mentioned below
SOURCE
DATASOURCE
INTEGRATIONID
SLOT_DATE
SLOT1
SLOT2
SLOT3
SLOT4
SLOT5
SLOT6
SLOT7
SLOT8
SLOT9
SLOT10
1
101
201111
100
100
200
100
100
100
300
300
300
300
1
101
2011112
200
200
200
200
100
100
100
100
200
300
TARGET
DATASOURCE
INTEGRATIONID
SLOT_DATE
SLOT_VALUE
SLOT MIN
SLOT_MAX
SLOT NUMBER
1
101
201111
100
1
2
SLOT1
1
101
201111
100
1
2
SLOT2
1
101
201111
200
3
3
SLOT3
1
101
201111
100
4
6
SLOT4
1
101
201111
100
4
6
SLOT5
1
101
201111
100
4
6
SLOT6
1
101
201111
300
7
10
SLOT7
1
101
201111
300
7
10
SLOT8
1
101
201111
300
7
10
SLOT9
1
101
201111
300
7
10
SLOT10
1
101
2011112
200
1
4
SLOT1
1
101
2011112
200
1
4
SLOT2
1
101
2011112
200
1
4
SLOT3
1
101
2011112
200
1
4
SLOT4
1
101
2011112
100
5
8
SLOT5
1
101
2011112
100
5
8
SLOT6
1
101
2011112
100
5
8
SLOT7
1
101
2011112
100
5
8
SLOT8
1
101
2011112
200
9
9
SLOT9
1
101
2011112
300
10
10
SLOT10
e
so basically i would first denormalize the data using the pivot column and then use min and max to get the slot_start and slot_end.
But then i
can get the min and max ... but not the orignal values as well.
Any thoughts would be appreciated.
ThanksIf you want to end up with one row per slot per datasource etc, and you want the min and max slots that have the same value as the current slot, then you probably need to be using analytic functions, like:
with t as
(SELECT 1 datasource,101 INTEGRATIONID, 201111 slotdate, 100 SLOT1, 100 SLOT2, 200 slot3, 100 slot4, 100 slot5, 100 slot6, 300 slot7, 300 slot8, 300 slot9, 300 slot10 FROM DUAL union all
SELECT 1, 101, 2011112, 200, 200, 200, 200, 100, 100, 100, 100, 200, 300 FROM DUAL),
UNPIVOTED AS
(SELECT DATASOURCE,INTEGRATIONID,SLOTDATE,1 SLOT,SLOT1 SLOT_VALUE
FROM T
UNION ALL
SELECT DATASOURCE,INTEGRATIONID,SLOTDATE,2 SLOT,SLOT2
FROM T
UNION ALL
SELECT DATASOURCE,INTEGRATIONID,SLOTDATE,3 SLOT,SLOT3
FROM T
UNION ALL
SELECT DATASOURCE,INTEGRATIONID,SLOTDATE,4 SLOT,SLOT4
FROM T
UNION ALL
SELECT DATASOURCE,INTEGRATIONID,SLOTDATE,5 SLOT,SLOT5
FROM T
UNION ALL
SELECT DATASOURCE,INTEGRATIONID,SLOTDATE,6 SLOT,SLOT6
FROM T
UNION ALL
SELECT DATASOURCE,INTEGRATIONID,SLOTDATE,7 SLOT,SLOT7
FROM T
UNION ALL
SELECT DATASOURCE,INTEGRATIONID,SLOTDATE,8 SLOT,SLOT8
FROM T
UNION ALL
SELECT DATASOURCE,INTEGRATIONID,SLOTDATE,9 SLOT,SLOT9
FROM T
UNION ALL
SELECT DATASOURCE,INTEGRATIONID,SLOTDATE,10 SLOT,SLOT10
FROM T)
select DATASOURCE,INTEGRATIONID,SLOTDATE,slot,slot_value,min(slot) OVER (partition by datasource,integrationid,slotdate,rn) minslot,
max(slot) OVER (partition by datasource,integrationid,slotdate,rn) maxslot
FROM
select DATASOURCE,INTEGRATIONID,SLOTDATE,max(rn) over (partition by datasource,integrationid,slotdate order by slot) rn,slot,slot_value
FROM
(SELECT DATASOURCE,INTEGRATIONID,SLOTDATE,slot,slot_value,
case when row_number() over (partition by datasource,integrationid,slotdate order by slot) = 1 or
lag(slot_value) over (partition by datasource,integrationid,slotdate order by slot) <> slot_value
then row_number() over (partition by datasource,integrationid,slotdate order by slot)
ELSE null
END rn
from unpivoted
order by DATASOURCE,INTEGRATIONID,SLOTDATE,slot -
Max, Min and Count with Group By
Hello,
i want the max, min and count of a table, which is grouped by a column
I need a combination of these two selects:
select
max(COUNTRY_S) MAXVALUE,
min(COUNTRY_S) MINVALUE
from
tab_Country
select
count(*)
from
(select COUNTRY_TXT from tab_Country group by COUNTRY_TXT) ;
The result should be one row with the max and min value of the table and with the count of the grouped by table, not the max and min of each group! - i hope you understand my question?
Is this possible in one SQL-select?
Thank you very much
Best regards
HeidiHi, Heidi,
HeidiWeber wrote:
Hello,
i want the max, min and count of a table, which is grouped by a column
I need a combination of these two selects:
select
max(COUNTRY_S) MAXVALUE,
min(COUNTRY_S) MINVALUE
from
tab_Country
select
count(*)
from
(select COUNTRY_TXT from tab_Country group by COUNTRY_TXT) ;
The result should be one row with the max and min value of the table and with the count of the grouped by table, not the max and min of each group! - i hope you understand my question?
Is this possible in one SQL-select?
Thank you very much
Best regards
Heidi
It's not clear what you want. Perhaps
SELECT MAX (country_s) AS max_country_s
, MIN (country_s) AS min_country_s
, COUNT (DISTINCT country_txt) AS count_country_txt
FROM tab_country
I hope this answers your question.
If not, post a little sample data (CREATE TABLE and INSERT statements, relevant columns only) for all the tables involved, and the results you want from that data.
Explain, using specific examples, how you get those results from that data.
Always say what version of Oracle you're using (e.g. 11.2.0.2.0).
See the forum FAQ: https://forums.oracle.com/message/9362002 -
How to get max and min salary in a table
How to get max and min salary in a table
SQL> select max(sal),min(sal) from emp;
MAX(SAL) MIN(SAL)
5512 800
SQL> -
In mdx how to get max date for all employees is it posible shall we use group by in mdx
in mdx how to get max date for all employees is it posible shall we use group by in mdx
example
empno ename date
1 hari 12-01-1982
1 hari 13-06-2000
by using above data i want to get max dataHi Hari3109,
According to your description, you want to get the max date for the employees, right?
In your scenario, do you want to get the max date for all the employees or for each employee? In MDX, we have the Max function to achieve your requirement. You can refer to Naveen's link or the link below to see the details.
http://www.sqldbpros.com/2013/08/get-the-max-date-from-a-cube-using-mdx/
If this is not what you want, please provide us more information about the structure of you cube, so that we can make further analysis.
Regards,
Charlie Liao
TechNet Community Support -
How to select records based on Max/Min on different columns and group by
I have a table with 5 columns(a,b,c,d,e), i need to select records based on MAX(c),Max(D) and Min(e) group by a,b. i am trying using : select max(c),max(d),min(e) from table group by a,b. this is not working. its giving me 1 6 1
a b c d e
1 1 1 2 1
1 1 1 6 4
1 1 1 6 3
when i group by a,b i am expecting the record 1 6 3
Please help me with this.. Thanks in advance....Hi,
Welcome to the forum!
962163 wrote:
I have a table with 5 columns(a,b,c,d,e), i need to select records based on MAX(c),Max(D) and Min(e) group by a,b. i am trying using : select max(c),max(d),min(e) from table group by a,b. this is not working. its giving me 1 6 1
a b c d e
1 1 1 2 1
1 1 1 6 4
1 1 1 6 3
when i group by a,b i am expecting the record 1 6 3It looks to me like "1 6 1" is the correct answer. You're asking for the lowest value of e, and 1 is lower than 3.
Maybe you don't want MIN (e). Explain why you want 3 (that is, how you decided that 3 is the correct value for the last column) and someone will help you code it.
Edited by: Frank Kulash on Sep 28, 2012 6:17 PM
Whenever you have a problem, you should psot CREATE TABLE and INSERT statements for your sample data. That way, the people who want to help you can re-create the problem and test their ideas. It often helps to clarify the problem, too. since this is your first message, I'll do it for you:
CREATE TABLE table_x
( a NUMBER
, b NUMBER
, c NUMBER
, d NUMBER
, e NUMBER
INSERT INTO table_x (a, b, c, d, e) VALUES (1, 1, 1, 2, 1);
INSERT INTO table_x (a, b, c, d, e) VALUES (1, 1, 1, 6, 4);
INSERT INTO table_x (a, b, c, d, e) VALUES (1, 1, 1, 6, 3);
COMMIT; -
How to get the MAX,MIN from the below table...
Hi,
Database is SQL2012 R2 Express and I have a table and would like to dig out the MAX,MIN value of a specifiied date (e.g 2014-11-03)
ThanksNope... It still output more than 1 value on the same date...
DL-01-BAT 13.00753 13.00753 10/10/2014
DL-01-BAT 13.01342 13.01342 10/10/2014
DL-01-BAT 13.02706 13.02706 10/10/2014
DL-01-BAT 13.03485 13.03485 10/10/2014
Raw data is
DL-01-BAT 13.00753 13.00753 10/10/2014 20:00
DL-01-BAT 13.01342 13.01342 10/10/2014 21:00
DL-01-BAT 13.02706 13.02706 10/10/2014 22:00
DL-01-BAT 13.03485 13.03485 10/10/2014 23:00
You mean after applying my suggestion?
I dont think so
See illustration below
declare @t table
Item VARCHAR(10), Reading VarChar(50),DateTimeReading DATETIME)
INSERT @t
VALUES
('DL-01-BAT', 13.00753,'10/10/2014 20:00'),
('DL-01-BAT', 13.01342,'10/10/2014 21:00'),
('DL-01-BAT', 13.02706,'10/10/2014 22:00'),
('DL-01-BAT', 13.03485,'10/10/2014 23:00')
DECLARE @Date datetime = '20141010'
SELECT Item,
MAX(Reading) AS [Max],
MIN(Reading) AS [Min],
DATEADD(dd,DATEDIFF(dd,0,DateTimeReading),0) AS [Date]
FROM @t
WHERE DateTimeReading >= @Date
AND DateTimeReading < DATEADD(dd,1,@Date)
GROUP BY Item, DATEADD(dd,DATEDIFF(dd,0,DateTimeReading),0)
Please Mark This As Answer if it solved your issue
Please Mark This As Helpful if it helps to solve your issue
Visakh
My MSDN Page
My Personal Blog
My Facebook Page -
Clicking installESD.dmg get invalid checksum on 09 Max mini ?
My 09 Max mini Os x snow leopard 10.6.8 4gb ram 250gb hdd
ive downloaded lion and get when opening installesd.dmg during verification "invalid checksum" ive downloaded twice and same occurance both times. really want to install and run OS X Lion. any ideas??What does Disk Utility > Verify Disk report on your hard drive?
-
Quicktime Pro Max/Min Frame for slideshow
Haven't bought QTpro yet, need to know if I can load 100's of JPG and play back and save as movie.
Thinking of using application for playback of time lapse images
What frame rate adjustments are possible and what are the max/min settings in the 'Image Sequence Settings'
Thanks,
A
G5 Mac OS X (10.4.8)Frame rate at import goes from 10 seconds per frame up to 60 frames per second. You can always adjust them again after import by adding scaled to a "dummy" audio file to get any frame rate you could possibly need.
I think someone found the image sequence file import maximum to be somewhere around 65,000 images. I've successfully made movies from a folder of over 5,000. -
I'm trying to create a mail merge label sheet and am getting one label per page- how do I get each on entry on same sheet?
Is there a "next entry" code?select phase_logid, orderid, phaseid, etc, max(statusid)
status
from yourtables
where whatever
group by phase_logid, orderid, phaseid, etc -
Max-instances-per-pk attribute
Does anybody know what is "max-instances-per-pk" attribute in
<entity-deployment> element in orion-ejb-jar.xml file?
I'm using oc4j version:
E:\oc4j\j2ee\home>java -jar oc4j.jar -version
Oracle9iAS (9.0.2.0.0) Containers for J2EEand when I deploy my CMP EJB I get this attribute added to my orion-ejb-jar.xml file with value 20!!!!!
And when I try to create (or findByPrimaryKey) many beans with
the same primary key, after 20 my server is hanging and I get timeout exceptions:
for (int i=0; i<100; i++) mybean.findByPrimaryKey("1");
when i==20 I get:
com.evermind.server.ejb.TimeoutExpiredException: timeout expired waiting for an instance
at com.evermind.server.ejb.DBEntityWrapperPool.getWrapperInstance(DBEntityWrapperPool.java:189)
at com.evermind.server.ejb.DBEntityEJBHome.getWrapperInstance(DBEntityEJBHome.java:135)
at CatalogHome_EntityHomeWrapper10.findByPrimaryKey(CatalogHome_EntityHomeWrapper10.java:302)
at pl.empolis.delta.modules.catalogman.CatalogManagerBean.getCatalogEntryByPublicID(CatalogManagerBean.java:56)
at CatalogManager_StatelessSessionBeanWrapper6.getCatalogEntryByPublicID(CatalogManager_StatelessSessionBeanWrapper6.java:734)
at java.lang.reflect.Method.invoke(Native Method)
at com.evermind.server.rmi.RMICallHandler.run(RMICallHandler.java:80)
at com.evermind.util.ThreadPoolThread.run(ThreadPoolThread.java:62)
How do I set this value to infinity?
Why I can not find any documentation about this?????
Please help,
ArturArtur -- max-instances-per-pk controls the size of the pool of wrapper instances for OC4J. I would just set it to a very large
integer value. It will be documented in the production release of the EJB guide but for now here is a section from
book. Also, the cache will be able to be disabled but that function was not in the pre-release. Lastly, we should be
posting some of the documentation very soon (look for an announcement) so that will help to clarify some things.
The wrapper instance is OC4J-generated wrapper code that provides for the
services requested in the deployment descriptor. Before the bean instance is
invoked, the client retrieves a handle to the wrapper instance. When the client
invokes the bean, the wrapper is associated with a bean instance.
The max-instances-per-pk attribute sets the maximum entity bean
wrapper instances allowed in its pool for a given primary key. An entity beans
wrapper code can be pooled if it is not used by a client.
The default maximum value is 50. Set the maximum wrapper instances as
follows:
<entity-deployment ... max-instances-per-pk="20"
</entity-deployment>
Set the minimum wrapper instances as follows:
<entity-deployment ... min-instances-per-pk="2"
</entity-deployment>
Thanks -- Jeff -
I have a project that is approximately 1 hour in length. This is the first project I am attempting to burn. I assigned a theme to the project and then proceeded to burn a DVD. Before the burn could actually start, PE crashed with a "blue screen" dump. I rebooted in Windows safe mode, then rebooted back into normal Windows mode. When I started PE and opened the project, nearly all of the themes were missing! It appears that only one theme per group remained.
What would have removed or hid the themes? I would have also expected all or none of the themes, rather than leaving just one per group. I was using a template in the "General" group, but the one that remained after the crash is not the one I had assigned to my project.
Does a reinstall restore the templates? If so, can I reinstall PE 4.0 from my CD without erasing, distroying, or losing the current projects I have created?
Thanks in advance for your comments!Hunt,
Before diving into the details of the items in the article, I did a few of the basic things:
stopped my anti-virus product (doh!)
stopped the temperature monitor software (doh!)
did a quick disk cleanup
turned off all trivial stuff in msconfig
I rebooted the system and started Premiere Elements. I had not attempted to reload the templates at that point, so I proceeded to "Burn to DVD". I selected the minimal quality and started the burn. That worked! Next I exited PE and restarted it and then was able to successfully "Burn to DVD" using the max setting for quality. As expected, it took a while to finish, but it also completed successfully! The resulting DVD looks and sounds great, so the rendering and burn phases seem to be working fine on my hardware.
I noticed on the CD that there is an option to load the themes, so I am going to try loading that today. I'll post more comments after I get the themes reloaded in case there are other steps involved in restoring those within the program.
Maybe you are looking for
-
Best Regards I would like to know which site I can download the sample application called Pet Store, I searched the web and all links lead me to the java.net site, but can not find where to download the. jar. I appreciate the attention.
-
Clean Install Mavericks... Time Machine backups...
Hey, I've been having some minor issues with the 'spinning beach ball'/system freezing up, or not even being able to boot up and having to re-install Mavericks... So I brought it in to a Apple store, and they suggested doing a clean install... I've h
-
AutoUnattend.xml is not completing
So I'm running into a problem with my AutoUnattend.xml. I needed to update my image, so I started from scratch after applying all necessary updates. It was taking far too long to update workstations after installing from the old image. The problem I'
-
Update errors for cs5 web premium (Mac)
Trying to do updates for cs5 web premium (Mac) but getting an update error. Support Chat said I had to ask in here. I am not getting a serial number prompt. I have registered my product already.
-
Geo load balancing and scaling
I am looking at the options for geographic load balancing and thinking of setting up 2 or 3 regions initially. Is there any data available for each of the regions in terms of latency for different countries/locations? I want to pick a number of key