Do a LEFT JOIN with a GROUP BY to find the MAX(timestamp): select e.empid, e.empname, e.status, max(timestamp) as lastusedts from employee e left join facilities f on e.empid = f.empid where e.status = 'active' group by e.empid, e.empname, e.status Alternatively, a correlated sub-select for the max-timestamp: select e.empid, e.empname, e.status,...

Full disclosure: I authored and maintain the hash package. Unless you have a hash with many key-value pairs and need the performance, standard R vectors with names will likely be a better solution. Here is one example: v <- c(a = 5, b = 2, c = 3, d =...

Modify the return signature of your method(s), assign the value to smallest (or biggest) and then return the variable. Like, public static int biggest(int nr1, int nr2, int nr3){ int biggest = 0; if (nr1>nr2 && nr1>nr3){ biggest = nr1; } else if (nr2>nr1 && nr2>nr3){ biggest = nr2; }...

oracle,plsql,exception-handling,oracle11g,max

No, it won't go into exception. MAX will not raise no_data_found as it will return a NULL value. See this: SQL> select max(a_id) from table_a; MAX(A_ID) ---------- SQL> select a_id from table_a; no rows selected SQL> is there any other alternative than taking the count() and then getting the value...

May be this helps library(dplyr) library(tidyr) add_rownames(df1) %>% gather(Var, Val, -x, -rowname) %>% extract(Var, into='Var', '([^0-9]*).*') %>% group_by(rowname, x, Var) %>% summarise(Mean=mean(Val), Min=min(Val), Max=max(Val)) Or using base R res <- do.call(rbind, lapply(split(names(df1)[-1], sub('\\d+$', '', names(df1)[-1])), function(x) { x1 <- df1[x] data.frame(x=df1[1],Mean=rowMeans(x1), Max=do.call(pmax, x1), Min=do.call(pmin, x1))})) data df1 <- structure(list(x =...

You can just find max(time_insert) and group by id. Take a look at sample query with src as ( select 1 as id, 'Accepted' as status, to_date('2015-05-05 01:00:00','yyyy-mm-dd hh24:mi:ss') as time_insert from dual union all select 1 as id, 'Failed' as status, to_date('2015-05-05 02:00:00','yyyy-mm-dd hh24:mi:ss') as time_insert from dual union...

sql,sql-server,tsql,group-by,max

You can do this a tiny bit more compactly with the nonstandard TOP WITH TIES clause: SELECT TOP (1) WITH TIES startdate , number , pc.name pc_name , gp.Name gp_name , P.Name FROM playperiod PD LEFT JOIN room R ON R.Roomid = PD.Roomid LEFT JOIN pc ON pc.PCid = PD.PCID...

Strings are ordered lexicographically, not by size. zara is the 'biggest' because it is last in the sort order, after marco: >>> 'zara' > 'marco' True >>> sorted(['zara', 'marco']) ['marco', 'zara'] oranges comes after apples, banana and cherries. >>> sorted(['apples', 'oranges', 'cherries', 'banana']) ['apples', 'banana', 'cherries', 'oranges'] If you wanted...

excel,if-statement,excel-formula,max,excel-2010

Well, I learned today that the And() function doesn't work inside of an array formula! In any case, try this: =MAX( IF(A3:A29>=$G$1, IF(A3:A29<=$G$2,$B$3:$B$29) ) ) (and don't forget to ctrl+shift+enter)...

std::max_element http://www.cplusplus.com/reference/algorithm/max_element/ std::min_element http://www.cplusplus.com/reference/algorithm/min_element/

SQLite can get values from the row that matches a MAX(), but this works only when there is a single MAX(). You have to use subqueries to look up the values: SELECT winery, (SELECT MAX(date) FROM tastings WHERE wine_id = wines.id AND status = 1 ) AS tasting_date, (SELECT score...

max,counter,tempo,max-msp-jitter

It sounds like you're really new to Max MSP and audio processing in general so I really can't stress the importance of understanding how audio processing works in general and how much you'll learn just going through all the built in tutorials in Max. Beat detection is a pretty complex...

In case salary sum is unique, you can calculate sum for each dept then order records in descending order by aggregated salary and fetch the first record (with the greatest salary): select dept , sum(salary) as salary from tbl group by dept order by salary desc limit 1 In case...

parallel-processing,max,opencl,gpgpu,barrier

Why the unroll part do not need to sync thread after each step is done? The sample is incorrect, a barrier is indeed required after each step. It looks like the sample is written in warp-synchronous style, which is a way of exploiting the underlying execution mechanism of the...

After you fit to find the best parameters to maximize your function, you can find the peak using minimize_scalar (or one of the other methods from scipy.optimize). Note that in below, I've shifted x[2]=3.2 so that the peak of the curve doesn't land on a data point and we can...

Start with a query which pulls everything you want for those Reefers which had at least one temperature alert: SELECT sub1.ReeferNo, a2.AlertDateTime, a2.ReceivedDateTime, a2.AlertType, a2.Temperature, a2.Location FROM ( SELECT a1.ReeferNo, Max(a1.AlertDateTime) AS MaxOfAlertDateTime FROM Alerts AS a1 WHERE a1.AlertType='Temperatures' GROUP BY a1.ReeferNo ) AS sub1 INNER JOIN Alerts AS a2...

You can keep three variables to store three largest values, and iterating through the array: You need to take care of three cases: When the current element greater than the largest element. Need to update second and third largest accordingly. When current element greater than second largest. Need to update...

android,max,min,android-datepicker

You can try replacing this line: return new DatePickerDialog(this, pDateSetListener, pYear, pMonth, pDay); By those: DatePickerDialog dpDialog = new DatePickerDialog(this, pDateSetListener, pYear, pMonth, pDay); DatePicker datePicker = dpDialog.getDatePicker(); Calendar calendar = Calendar.getInstance();//get the current day datePicker.setMaxDate(calendar.getTimeInMillis());//set the current day as the max date return dpDialog; in the same way you...

You can do this way: SELECT YEAR ( MAX(date) ) as year, MONTH ( MAX(date) ) as month, DAY ( MAX(date) ) as day, HOUR( MAX(date) ) as hour, MINUTE( MAX(date) ) as minute, SECOND( MAX(date) ) as second from table ...

max = inst[i][j]; Should be max = Math.max(max, ints[i][j]); and... for(int j = 0; j < ints.length){ should be for(int j = 0; j < ints[i].length; j++){ So... public static int maxMatrix(int [][] ints) { int max = ints[0][0]; for(int i = 0; i < ints.length; i++) { for(int j...

sql-server,tsql,sql-server-2012,max,sql-insert

You could use a CTE with just one column that is the maxtime from tb2. Then join on the CTE and reference it when checking for if its the max or not. WITH aggregateTime (maxTime) AS ( SELECT MAX(STime) AS maxTime FROM tb2 ) INSERT INTO tb1 (id, EMPNO, Street1)...

One way would be to use a join to fetch them all like so: SELECT I.* FROM Items I JOIN (SELECT MAX(price) AS maxprice FROM items) M ON I.price=M.maxprice; ...

excel,if-statement,excel-formula,max,worksheet-function

If your data is in three columns (starting A2) then maybe: =IF(B2="MD",MAX(C$1:C1)+1,"") ...

The main problem here is the last line: else (temp)))))) The parentheses are incorrect here—the else keyword needs to be within the parens. Changing that to this: (else temp)))))) ...fixes the algorithm. You also aren't calling maxmin properly—it needs a list, not a series of parameters. Your final line of...

Try using CASE and GREATEST(): SELECT CASE GREATEST(@rnkma, @rnkmb, @rnkmc, @rnkmd) WHEN @rnkma THEN [email protected]' WHEN @rnkmb THEN [email protected]' WHEN @rnkmc THEN [email protected]' WHEN @rnkmd THEN [email protected]' END name, GREATEST(@rnkma, @rnkmb, @rnkmc, @rnkmd) value (...) ...

Function std::max provides a way to find the max value of exactly two numbers. Use std::max_element to work with ranges: FinalValue = *std::max_element(std::begin(values), std::end(values)); Note 1: the above assumes that the range std::begin(values)..std::end(values) is not empty. Passing an empty range results in undefined behavior on dereference of std::max_element result, which...

This could be done with order by limit, so all you need to add the following at the end of the given first query order by idevent desc limit 1 ...

Use order by and limit: SELECT COUNT(*) AS count, field1, field2, field3 FROM someScheme.someTable GROUP BY field1, field2, field3 ORDER BY COUNT(*) DESC LIMIT 1; Note: this only returns one example of the maximum. If you want all possible rows, then it is more complicated: SELECT COUNT(*) AS count, field1,...

java,elasticsearch,max,histogram,aggregation

I think I found a solution: $ curl -XGET 'http://localhost:9200/localhost.localdomain/SET_APPS/_search?pretty=true' -d' { "aggregations" : { "time_hist" : { "histogram" : { "field" : "time", "interval" : 10125000, "order" : { "_count" : "asc" }, "min_doc_count" : 0, "extended_bounds" : { "min" : 1429010378445, "max" : 1431602378445 } }, "aggregations" :...

sql,postgresql,max,aggregate-functions

Use GREATEST : SELECT GREATEST(1, 100); ┌──────────┐ │ greatest │ ├──────────┤ │ 100 │ └──────────┘ (1 row) ...

excel,if-statement,max,excel-2010,array-formulas

Please try: =MAX(IF(A:A=A1,B:B)) entered with Ctrl+Shift+Enter and copied down to suit. I'm afraid this could be quite slow. I did not limit the range because I assumed 107,000 rows was an approximation. However this is slow even for 1,000 rows, so for emphasis I repeat part of @XOR LX's comment:...

Try library(dplyr) as.data.frame(m1) %>% group_by(id)%>% summarise_each(funs(max=max(., na.rm=TRUE))) # id sample1 sample2 sample3 #1 1 21282.5 3342 22202 #2 2 18558.0 3047 NA #3 3 3709.0 2338 5709 #4 4 1.0 2 1 Or aggregate(.~id, as.data.frame(m1), FUN= max, na.rm=TRUE, na.action=NULL) NOTE: I am guessing you have real NAs in the dataset...

The error is 1111: invalid use of group function. As for why specifically MySQL has this problem I can really only say it is part of the underlying engine itself. SELECT MAX(2) does work (in spite of a lack of a GROUP BY) but SELECT MAX(SUM(2)) does not work. This...

select count(VIN), Category from STOCK having count(VIN)=(select max(count(VIN)) from STOCK group by Category ) OR count(VIN)=(select min(count(VIN)) from STOCK group by Category ) group by Category; ...

visual-studio-2012,max,powerpivot,calculated-columns,dax

Generally, as @mmarie suggests, you are better dealing with this kind of problem with a measure rather than a calculated column. That said, sometimes you just need that extra column (usually to use as a dimension). Assuming you have a table called recordsFact, this gives the MAX of that record:...

If you want the model, use union all and order by. You don't specify the database, so here is the ANSI standard solution: SELECT model, price FROM ((SELECT model, price FROM PC) UNION ALL (SELECT model, price FROM Laptop) UNION ALL (SELECT model, price FROM printer) ) p ORDER BY...

String a compares as the biggest because it starts with 9 and the other strings start with 1 and 8. Python therefore returns '9:30' as the maximum value out of those three strings.

Changing the code to parse the duration values to Int fixes the problem together with processing them with d3.forEach function. See below: d3.csv("test.csv", function(error, data) { console.log(data); data.forEach(function(d) { d.date = d.date; d.value = d.value; d.duration = parseInt(d.duration); }); var maximum = d3.max(data, function(d) { return d.duration; }); console.log("max is...

I created a sample data. Hope this is what you need df <- data.frame(names=c('A','A','A','A','B','B','B','C','C','C','C','C'),Length=c(1:12)) library(plyr) df2<- ddply(df, "names", subset, Length==max(Length)) ...

Accumarray accepts functions both anonymous as well as built-in functions. It uses sum function as default. But you could change this to any in-built or anonymous functions like this: In this case you could use max function. in = horzcat(a,b).'; [uVal,~,idx] = unique(in(:,1)); out = [uVal,accumarray(idx,in(:,2),[],@max)].' ...

every element of the vector L must be less than or equal to 1. This should be written as a set of constraints, not a single constraint. Artificially bundling the constraints L(1)<=1, L(2)<=1, ... into one constraint is just going to cause more pain to the solver. Example with...

Use GREATEST function SELECT Rollno, GREATEST (mark1, Mark2, mark3) AS Maxv FROM yourtable ...

I assume that you want the OpenGL content to end up in the same output window as the web cam capture. I would advise sending the matrix from the webcam input to a jit.gl.texture object, then rendering it with a jit.gl.videoplane, like so: ----------begin_max5_patcher---------- 348.3ocwSsraCCBD7L9q.wYWKamG8wo7eTEEgsWkPDFr.bhihx+dMKFklFop V0V0Kf2gcmc7vx4DBqRO.VF8E5qTB4bBgfPd.xTLg0xGpkbKlFSAG0U6Yogi bvfCg2KbYakYGDMftSxU.ck+rdCPOBU071XEp9VgRBNjshqf5dWDsbBsi6p2 ITa2XfZWPiKVjkmRKJCaOOyuUVlkSWOUi0cRBnhhMTzfgih9gYQrPybm5f.s...

If you want to apply substring to each item in the sequence, try let $abc := doc("file:///some_local_file")//AOSCAT_MetricDetail//table[@class="pretty-table"]//tr/td[13] return <li>{ max($abc/substring(.,1,1)) }</li> (untested). If that doesn't work then you can definitely do it with an explicit for: let $abc := doc("file:///some_local_file")//AOSCAT_MetricDetail//table[@class="pretty-table"]//tr/td[13] return <li>{ max(for $x in $abc return substring($x,1,1)) }</li> ...

mysql,sql-order-by,max,distinct,where

The WHERE clause in my query is to keep out user_ids where the support_date is inside a range of the past 7 days. You can rephrase it like this: The WHERE clause in my query is to select user_ids where highest support_date is outside a range of the past...

You could use which with(tweetcount, timeround[which(n== max(n))-1]) If there is only a single max value tweetcount$timeround[which.max(tweetcount$n)-1] ...

You can keep track of the maximum value without the need of an array. The solution is to initialize the maximum at 0, then for every number, we keep only the maximum of the previous maximum and the current number. The algorithm goes like this : double max = 0;...

A generic hash table is not a sorted list of elements. So it's going to be an O(n) operation to find the min() and max() of a given table.

Since you only want one phone number (with the max value), break when one is found: max_value = values.values.max #store the max value to prevent computing it multiple times values.each { |k, v| puts k; break if v == max_value } # ^^^^^ ...

Convert list_value to a NumPy array and then apply numpy.ndarray.max on 0th axis: >>> arr = np.array(list_value) >>> arr.max(axis=0) array([9, 8, 9]) ...

Use the CSS properties word-wrap and word-break like shown below: #test { width: 20%; word-break: break-all; word-wrap: break-word; } <table> <tr> <td id="test"> <ul> <li>HiByeHiByeHiByeHiByeHiByeHiByeHiByeHiByeHiByeHiByeHiByeHiBye</li> </ul> </td> <td> Box 2: Where is its 80% width? </td> </tr> </table> ...

javascript,arrays,for-loop,max

To start, we've seen no numbers, and the code assumest the biggest is 0 or larger: var biggest = 0; We'll look at each number in the list: for(i=0; i < num.length; i++ ) { Is the current number bigger than the biggest we've seen? if( num[i] > biggest )...

Since the largest 13 digit integer can be stored using 6 bytes you need a type which will store at least 6 bytes, that type is a long long which can hold 8 bytes. So instead of int x=100; use long long x=100; ...

swift,max,nsdecimalnumber,roundup

let x = NSDecimalNumber(string:"10") let y = NSDecimalNumber(string:"3") let total = x.decimalNumberByDividingBy(y).decimalNumberByRoundingAccordingToBehavior( NSDecimalNumberHandler(roundingMode: NSRoundingMode.RoundUp, scale: 0, raiseOnExactness: false, raiseOnOverflow: false, raiseOnUnderflow: false, raiseOnDivideByZero: false)) // 4 ...

python,max,time-complexity,complexity-theory

Recursive method decreases the input size by one each call, so it's theoretically linear (since you're essentially doing a linear search for the maximum). The implementation of Python's lists is going to distort a timer-based analysis.

The most efficient way to do this sort of analysis is generally to use analytic functions (window functions). Something like SELECT first_name, last_name, salary, department_id FROM (SELECT e.*, rank() over (partition by department_id order by salary desc) rnk FROM employees e) WHERE rnk = 1 Depending on how you want...

You could use UNION ALL together with ROW_NUMBER: ;WITH CteUnion AS( SELECT id_contract = c.id_contract, price = cd.price, date_sign = c.date_sign FROM contracts c LEFT JOIN contracts_data cd ON cd.id_contract = c.id_contract UNION ALL SELECT id_contract = c.id_contract, price = ad.price, date_sign = a.date_sign FROM contracts c LEFT JOIN contracts_anexes...

What your expression asks for is "give me all $x where there is a num_bids, anywhere in the document, which is equal to $max." Which is different than "give me all $x for which its own num_bids is equal to $max." The following should do (not tested): let $in :=...

Use a JOIN with subqueries. select tpt.AlbumId from ( select Album.AlbumId, Sum(Track.UnitPrice) as Total from Album inner join Track on Album.AlbumId = Track.AlbumId group by Album.AlbumId ) tpt JOIN ( select Sum(Track.UnitPrice) as Total from Album inner join Track on Album.AlbumId = Track.AlbumId group by Album.AlbumId ORDER BY Total DESC...

you can remove the from numpy import * unless you are using it elsewhere. Aside from that using a list works fine. To get the max just call max(B) as follows: Z=int(raw_input("What is the atomic number?")) a1,a2,a3,a4 = 15.67,17.23,0.75,93.2 B = [] for A in range(Z, 3*Z): if A%2==1: a5=0...

You can allocate the array dynamically: #include <stdlib.h> char *a = (char*)malloc(100*sizeof(char)); if (a == NULL) { // error handling printf("The allocation of array a has failed"); exit(-1); } and when you want to increase its size: tmp_a = realloc(a, 10000*sizeof(char)); if ( tmp_a == NULL ) // realloc has...

max=0; for (count=0;count<SIZE;count++){ if (myArray[count]>max){ max = myArray[count]; } } You need change all <= SIZE to < SIZE ...

excel,excel-formula,max,concatenation,worksheet-function

Please try: =MAX(D:D)&"("&INDEX(A:A,MATCH(MAX(D:D),D:D,0))&")" will only return one year even if the maximum value arises in more than one year....

python,list,dictionary,lambda,max

There are a few mistakes. The nearest correction can be:- >>> max(h, key=lambda k : h[k][2]) '1' >>> h={'1':['a','3','56'],'2':['a','2','125']} >>> max(h, key=lambda k : int(h[k][2])) '2' >>> maxval = max(h, key=lambda k : int(h[k][2])) >>> h[maxval] ['a', '2', '125'] The mistakes can be listed as The key is evaluated for...

In MySQL, the query is a bit more complicated. One method is using two subqueries with aggregation: select t.* from (select t.id, count(*) as A_plus from take t where t.grade = 'A+' group by t.id ) t where t.A_plus = (select max(A_plus) from (select t.id, count(*) as a_plus from take...

mysql,max,directed-acyclic-graphs

You should be able to use the GREATEST() function in MySQL. Try this: SELECT GREATEST( (SELECT MAX(id_item) FROM material), (SELECT MAX(id_collection) FROM material)); This will select the largest item, whether that's the MAX(id_item) or MAX(id_collection). EDIT Something that may look a little cleaner. The GREATEST() function takes the largest of...

There is no MAX or GROUP BY. It is just: SELECT TOP 1 cn.Note, cn.Date FROM CarsNote cn WHERE cn.CustomerID = '80' AND cn.Type = 'INFO' ORDER BY cn.Date desc; ...

This should do it: var maxFamilyVersion = (from ic in dsIndexContract join i in dsIndex on ic.INDEX_ID equals i.INDEX_ID where i.INDEX_SHORT_NAME.CONTAINS(strindex) && ic.TENOR == d.TERM select ic.INDEX_FAMILY_VERSION).Max(); ...

Try library(dplyr) sample %>% group_by(Cust_no) %>% filter( Total==max(Total)) # Txn_date Cust_no Acct_no cust_type Credit Debit Total #1 09DEC2013 17382 601298644 I 1500 0 1500 #2 19DEC2013 17382 601298644 I 1500 0 1500 Or library(data.table) setDT(sample)[, .SD[Total==max(Total)] ,Cust_no] # Cust_no Txn_date Acct_no cust_type Credit Debit Total #1: 17382 09DEC2013 601298644 I...

If cummax isn't working then I came up with this little function function m = cummax2(x) [X, ~] = meshgrid(x, ones(size(x))); %replace elements above diagonal with -inf X(logical(triu(ones(size(X)),1))) = -inf; %get cumulative maximum m = reshape(max(X'), size(x)); end ...

sql-server,tsql,group-by,max,aggregate-functions

You are grouping by the aggregate in your query. You need to group by the scalar columns instead. In this case, group by f.fizz_name, fu.foo_name

Your query as written would give you the largest value of Filiyal (alphabetically) from the set of banks that have an approved status. If what you are looking to find is the Filiyal with the most approved records, then you need to have something that counts the records that are...

You should do something like # create an empty list object myListofNA = [] for d in range(0,2): datei = filenames[d] aMolecule = openfiles(datei) myNA = aMolecule[3] print myNA # each time append a new entry to the list myListofNA.append(myNa) # search the maximum element of the list print max(myListofNA)...

Here is one way of doing it using jQuery to determine when to start wrapping the text. The only hard-coded parameter is the max width of 500px. You need to wrap your content in the first column in a div. The trick is to initially force the div to expand...

Skip the GROUP BY, return a row if no other row with same Employee_Number and Cap_Id but a later date exists! SELECT Employee_Number, Cap_Id, Score, Date_Added FROM Scores s1 WHERE NOT EXISTS (select 1 from Scores s2 where s1.Employee_Number = s2.Employee_Number and s1.Cap_Id = s2.Cap_Id and s1.Date_Added < s2.Date_Added) Will...

python,lambda,max,xrange,matrix-decomposition

First, isn't the line for ID simply the identity matrix? Yes. Second, I can't really understand the line for row.... See this for a discussion about the max/key/lambda interaction. To answer "what is i?", its the argument to the lambda function, i could equivalently be x for foo. (For...

This query based on analytic functions lag() and lead() gives expected output: select id, nid, point from ( select id, point, p1, lead(id) over (order by id) nid from ( select id, point, decode(lag(point) over (order by id), point, 0, 1) p1, decode(lead(point) over (order by id), point, 0, 2)...

One approach would be to store the previous two values lines in two variables, and use a third variable to store the line. So you could get the local minimum like this: awk 'prev!=""&&prev<=prev2&&prev<=$2{print line}{prev2=prev;prev=$2;line=$0}' file and the local maximum like this: awk 'prev!=""&&prev>=prev2&&prev>=$2{print line}{prev2=prev;prev=$2;line=$0}' file ...

Try this: update table1 inner join (SELECT max(`reduction`) as maxprice, id FROM table2 group by id ) t on table1.id = t.id SET table1.price = table1.price - t.maxprice ...

Not tested, but does something like this work? var resultado = (from Users in ctx.Users select new { Name= Users.Name, MaxDate=(from c in ctx.Calls where c.IdUser == Users.IdUser select c.CallDate).Max() }).ToList(); ...

I've never used bigquery before but something like this should work: SELECT movieID, CASE WHEN F_rate >= M_rate THEN F_rate ELSE M_rate END max_rating, CASE WHEN F_rate > M_rate THEN 'Females Rated it Higher' WHEN F_rate < M_rate THEN 'Males Rated it Higher' ELSE 'Rated Equal' END AS who_rated_it_higher, ABS(F_rate...

You probably want the highest date, but all other columns, too. You need a Windowed Aggregate Function for this: SELECT * FROM ( SELECT student_crs_hist.id_num, name_format_view.last_first_middle_suf, year_term_table.pesc_session_type, student_crs_hist.yr_cde, student_crs_hist.trm_cde, student_crs_hist.TRANSACTION_STS, year_term_table.TRM_BEGIN_DTE, -- group maximum = maximum date per id_num MAX(TRM_BEGIN_DTE) OVER (PARTITION BY student_crs_hist.id_num) AS maxDate FROM student_crs_hist, name_format_view, year_term_table...

sql,ms-access-2007,max,average

The problem is that the maximum of prod and the maximum of area are rarely in the same row. You should also learn to use explicit join syntax. A simple rule: never use a comma in the from clause. This may be what you want: SELECT temp.hhid, temp.country, temp.max_prod, temp.max_area,...

F# compares lists element by element. As 'B' > 'A' so it considers first list > second (lexicographic order) and breaks further comparison. You can use .Length property on list to compare lengths. Like this for example; let longest = if xs.Length > ys.Length then xs else ys Result: val...

algorithm,sum,max,hungarian-algorithm

This looks like the Transportation Problem to me. It can be solved using the Hungarian Algorithm though. First let's set up the matrix for the Hungarian Algorithm. The Hungarian Algorithm is used to find the minimum sum. To make it solve a maximum sum problem you would first have to...

You can get the min and max rows separately with df1[which.max(df1[,2]),] Or df1[which.min(df1[,2]),] For plotting, may be df2 <- subset(df1, Number %in% c(min(Number), max(Number))) m1 <- t(df2[,2]) colnames(m1) <- df2[,1] barplot(m1) Update Using the example in the image, dfN <- data.frame(Col1=c('Controlli di Polizia Giudiziaria', 'Ricrosi a seguito di contravvenzioni', 'Ordinanze...

You simply need to GROUP your results by theme and module: SELECT theme, module, MAX(changed) FROM table_name GROUP BY theme, module ...

This will provide the output of the bird with highest age Modification a<-c("bird1","bird2","bird1","bird3","bird2","bird2") b<-c(32,45,35,25,51,47) compined_birds<-data.frame(animal=a,max=b) compined_birds$animal[which.max(compined_birds$max)] ...

sql,postgresql,select,max,psql

This is a classic usecase for the group by clause to return only distinct combinations of athlete and category. Then, max(points) could be applied to each combination: SELECT athlete, category, MAX(points) FROM mytable GROUP BY athlete, category ...

Find the max index of each value seen in x: xvals <- unique(x) xmaxindx <- length(x) - match(xvals,rev(x)) + 1L Rearrange xvals <- xvals[order(xmaxindx,decreasing=TRUE)] xmaxindx <- xmaxindx[order(xmaxindx,decreasing=TRUE)] # 2 4 1 3 # 5 4 3 2 Select from those: xmaxindx[vapply(1:6,function(z){ ok <- xvals < z if(length(ok)) which(ok)[1] else NA_integer_...

You can do this in several ways. One method would use join with an explicit aggregation. However, because you only want one column, I think a correlated subquery is simpler to code: select t1.*, (select max(t2.value) from table2 t2 where t2.date between t1.date1 and t1.date2 ) as maxvalue from table1...

Try this: SELECT ReservationStayID, NonRoombundleID, Tot, CONVERT(VARCHAR, DATEPART(yyyy, DATEADD(month, M,'1970-1-1')))+'-'+CONVERT(VARCHAR,DATEPART(month, DATEADD(month, M,'1970-1-1'))) AS [Month] FROM ( SELECT ReservationStayID, NonRoombundleID, COUNT(*) AS Tot, DATEDIFF(month, '1970-1-1', staydate) m, ROW_NUMBER() OVER ( partition by ReservationStayID, DATEDIFF(month, '1970-1-1', staydate) ORDER BY Count(*) DESC ) AS rownum FROM ResStayNonRoomBundle GROUP BY ReservationStayID, NonRoombundleID, DATEDIFF(month, '1970-1-1',...

If you want to do different things based on which of three variables has the highest value, you can't do better than: if (x > y && x > z) { // do stuff for when x is biggest } else if (y > x && y > z) {...