SQL Sorting in 'Union All' Condition |
In the first select you must have column with alias A
Select col1 as a [...] from [a] inner join [b] on a.[] = b.[] where []
Union All
Select [] from [a] inner join [b] on a.[] = b.[] where []
Union All
Select [] from [a] inner join [b] on a.[] = b.[] where []
Union All
Select [] from [a] inner join [b] on a.[] = b.[] where []
order by a
|
Sorting objects based on condition |
This should do the trick:
temp_array = @products.group_by(&:name)
@filtered_products = temp_array.map do |name, products|
products.sort{ |p1, p2| p2.revision <=> p1.revision }.first
end
Don't hesitate to ask details if you need ;)
|
Mongodb / Jongo sorting then limit, vs, limit then sorting |
In normal queries, sort is processed first, then skip, and then limit, no
matter in which order you add them to your cursor object.
The aggregation framework will execute the $sort, $skip and limit operators
in their order of appearance in the pipeline.
|
mongodb, sorting by geoNear and date? |
There's no direct way to use $near or $nearSphere and sort by another
field, because both of these operators already sort the results of doing a
find(). When you sort again by 'date', you're re-sorting the results. What
you can do, however, is grab results from the $nearSphere incrementally,
and sort each set of results. For example:
function sortByDate(a, b) { return a.date - b.date; }
// how many results to grab at a time
var itersize = 10;
// this will hold your final, two-way sorted results
var sorted_results = new Array();
for (var i=0, last=db.coll.count(); i<last-itersize; i+=itersize) {
var results = db.coll.find( {"date":{$gte:date},
// longitude, then latitude
"location":[lng, lat]}
).skip(i).limit(itersiz
|
MongoDB sorting and limit inside an array |
There is a sort and slice operator that can be used in conjunction when you
push the messages into the document arrays:
http://docs.mongodb.org/manual/reference/operator/sort/
http://docs.mongodb.org/manual/reference/operator/slice/
They keep your array sorted and limited respectively.
|
Efficiently sorting the results of a mongodb geospatial query |
When there is a huge result matching particular box, sort operation is
really expensive so that you definitely want to avoid it.
Try creating separate index on relevance field and try using it (without 2d
index at all): the query will be executed much more efficiently that way -
documents (already sorted by relevance) will be scanned one by one matching
the given geo box condition. When top 10 are found, you're good.
It might not be that fast if geo box matches only small subset of the
collection, though. In worst case scenario it will need to scan through the
whole collection.
I suggest you to create 2 indexes (loc vs. relevance) and run tests on
queries which are common in your app (using mongo's hint to force using
needed index).
Depending on your tests results, you may even want to
|
Distinct sorting and grouping with MongoDB aggregation framework |
Its actually a pretty easy fix if you think about how the aggregation
framework is described.
Taken from the docs:
Conceptually, documents from a collection pass through an aggregation
pipeline, which transforms these objects as they pass through. For
those familiar with UNIX-like shells (e.g. bash,) the concept is
analogous to the pipe (i.e. |) used to string text filters together.
You may have read that before, but the reason to explain that again is that
you can pass operations into that pipeline in just about any order - and
more than once. Where as in MYSQL for example, LIMIT is always listed at
the end of the query and applies to the result set after all other grouping
functions.
In MongoDB, the operations are run in the order you've added them to the
pipeline. So ord
|
MongoDB query with condition on multiple records |
I don't think it's possible with one query. But you can get all B you want
with aggregate and then query database for that B:
db.test1.aggregate(
[
{$group: {_id: "$B", count: {$sum:1}}},
{$match: {count:1}}
]
)
will return you all B for which there only one record in your collection.
|
MongoDb java async driver : What is the correct query for sorting and limiting values from a collection |
I don't think that the Aggregation framework is the right choice here. I
would just do a straight 'find'. There is a Find class and nested
Find.Builder class for constructing the more complex queries.
import static com.allanbank.mongodb.builder.QueryBuilder.where;
import com.allanbank.mongodb.MongoClient;
import com.allanbank.mongodb.MongoCollection;
import com.allanbank.mongodb.MongoFactory;
import com.allanbank.mongodb.MongoIterator;
import com.allanbank.mongodb.bson.Document;
import com.allanbank.mongodb.builder.Find;
import com.allanbank.mongodb.builder.Sort;
public class StackOverFlow {
// SELECT * FROM collect
// WHERE time >= input1 AND userId = input2
// ORDER BY time DESC
// LIMIT 30
public static void query(long input1, String input2) {
MongoCl
|
Defining Multiple Comparators for Sorting and Reverse Sorting Appcelerator Backbone Models |
To sort in descending order for strings(case insensitive) or just numbers,
try this:
var sort_descending = false; /* assuming you are able to set this variable
when you need to sort */
var sort_attribute_name = "title"; /* assuming you can set the attribute
name on which you want to sort */
book_list.comparator = function(book){ /* book_list is an instance of
book_collection */
if(sort_descending){
if(isNaN(book.get(sort_attribute_name)){
var str = book.get(sort_attribute_name);
str = str.toLowerCase();
str = str.split("");
str = _.map(str, function(letter){
return String.fromCharCode(-(letter.charCodeAt(0))); /* from an
SO answer*/
});
}
return -book.get(sort_attribute_name);
}
return book.get(sort_attribute_name);
};
|
CUDA parallel sorting algorithm vs single thread sorting algorithms |
Sorting is an operation that has received a lot of attention. Writing your
own sort isn't advisable if you are interested in high performance. I
would consider something like thrust, back40computing, moderngpu, or CUB
for sorting on the GPU.
Most of the above will be handling an array at a time, using the full GPU
to sort an array. There are techniques within thrust to do a vectorized
sort which can handle multiple arrays "at once", and CUB may also be an
option for doing a "per-thread" sort (let's say, "per thread block").
Generally I would say the same thing about CPU sorting code. Don't write
your own.
EDIT: I guess one more comment. I would lean heavily towards the first
approach you mention (i.e. not doing a sort per thread.) There are two
related reasons for this:
Most
|
unable to set variable in OR condition when the first condition fails inside a batch file |
example (prints 0 if found, otherwise 1):
set /a path_check=0
echo %PATH% | findstr /i "C:\Windows\System32;" 2>NUL || set /a
path_check=1
echo %path_check%
|
Thinking sphinx search with or condition didnt find both condition data |
To be honest, I'm not entirely sure why this is happening - it's a Sphinx
issue though, not Thinking Sphinx (so I've added the Sphinx tag). A
work-around is to wrap both search options in double-quotes:
fields << %q{(@description "#{params[:oiloiliness]}" |
"#{params[:oiloiliness].gsub(/[^0-9A-Za-z]/, '')}" )}
Also: you may want to consider adding hyphen to your list of ignore_chars
via config/thinking_sphinx.yml.
|
Suppress a duplicate row in SQL Server 2005 based on condition and list remaining rows that don't meet the condition |
If Hazard is blank or 'Y' then you can use MAX() and GROUP BY to get your
desired output:
SELECT SHPMNT_NO, TOT_WEIGHT, MAX(HAZARD) 'HAZARD'
FROM YourTable
GROUP BY SHPMNT_NO, TOT_WEIGHT
This will also work if Hazard is 'Y' or 'N'.
|
Chaining Parallel Tasks to an End Condition or Error Condition |
You would need to add a continuation to all of the tasks, 1-4, with the
error handling case to allow an error in any of them to call that function.
For convenience you could create a method to add the same continuation to a
collection of tasks. Here's one (feel free to add others for the other
overloads of ContinueWith as needed):
public static IEnumerable<Task> ContinueWith(this
IEnumerable<Task> tasks
, Action<Task> continuation, TaskContinuationOptions options)
{
return tasks.Select(task => task.ContinueWith(continuation,
options))
.ToList();//important for this ToList to be here;
//we want the continuations to be added now, not when the result is
iterated
}
This allows you to write:
var errorTasks = new[]{task, task2, task3, task4}
.C
|
Passing Condition as string to another function's if condition-java |
You can create a method, and place it in CellColorChanger class:
private boolean checkCondition(){
return /* whatever condition like: */ (row == 2 && column == 2)
|| (row == 6 && column == 1) || (row == 1 && column == 2)
|| (row == 4 && column == 1);
}
Call this function on passed CellColorChanger object, whenever you want the
condition to be re-evaluated.
|
JS object sorting date sorting |
Both console.log show the same array because when you use
console.log(sortable), sortable is passed by reference, and console output
happens AFTER finishing your script - when sortable has been already
sorted.
Making your code simple:
var arr = [3,2,1];
console.log(arr); // Produces `[1,2,3]` because its printed
// to the console after `arr.sort();`
arr.sort();
console.log(arr); // Produces `[1,2,3]`, as expected
Demo: http://jsfiddle.net/Rfwph/
Workaround
If you want to be able to do console.log with an array to see it before
being modifyed, you can use .slice(0) to copy the array, i.e. to obtain
another array which contains the same elements as your array.
var arr = [3,2,1];
console.log(arr.slice(0)); // [3,2,1]
arr.sort();
console.log(arr); // [1,2,3]
Demo:
|
C++ Bubble Sorting and Selection Sorting |
#include <iostream>
#include <string>
#include <iomanip>
using namespace std;
void sortArray (int [ ], int ) ;
void showArray (int [ ], int ) ;
int count = 0;
int main ()
{
const int SIZE = 6;
int values[SIZE] = {7, 2, 3, 8, 9, 1} ;
cout << "The unsorted values are:
";
showArray (values, SIZE) ;
sortArray (values, SIZE) ;
cout<< "The sorted values are:
" ;
showArray (values, SIZE) ;
return 0;
}
void sortArray (int array [ ], int SIZE)
{
int temp;
bool swap;
do
{ swap = false;
for (int count = 0 ; count < (size - 1 ) ; count ++)
{
if (array [count] > array [count + 1] )
{
temp = array [count] ;
array [count] = array [count + 1] ;
array [count + 1] = temp ;
swap = true ;
count++;
dispCount();
}
}
} while (swap) ;
}
void dispCount(){
cout <<
|
cakephp condition can't list out the condition with upline value |
'conditions' => 'id < '.$upline['User']['group_id']
should be
'conditions' => array( 'id < '.$upline['User']['group_id'] )
Also
'conditions' => 'id > '.$upline['User']['tgame_master_id']
should be
'conditions' => array( 'id > '.$upline['User']['tgame_master_id'] )
|
Sqlite query using where condition having more than one condition to satisfy |
May this help you:
Replace your query with these lines..
public Cursor query(int id){
return myDataBase.query("question", null,"_id = "+id+ " AND " + "chek
="+number,null, null, null, null);
keep space between the double quotes in And :" And " otherwise the string
will be Example: _id=3And check =9
|
including a condition dynamically based on another condition |
Should be pretty straightforward :
select --------
from table
left outer join....
where (Condition A IS NULL) OR (condition A AND condition B)
UPDATED: For your conditions:
where (a.column is null) or (a.column='123' and c.column='456')
It will include a a row if it's a.column is null or if bot a.column and
c.column have valid values.
|
MongoDB errors: mongodb-10gen E: Sub-process /usr/bin/dpkg returned an error code (1) |
This is due to some corruption within the package manager dpkg itself, this
thread from Ask Ubuntu:
http://askubuntu.com/questions/195950/package-system-broken-e-sub-process-usr-bin-dpkg-returned-an-error-code-1
lists some solutions, more specifically the editing of the status file has
been noted as one that always works.
|
Nodejs, MongoDB (node-mongodb-native). FindAndModify finds doc, but doesn't update it |
In findAndModify, there is one more parameter which you can set, to return
the old document(before update) or new document ( after update ). I am
guessing this must be the issue. For confirmation, for the existing
findAndModify() command, after this command is run, check that updated
document from the mongo console, it must be changed.
|
query based on matching elements in DBRef list for mongodb using spring-data-mongodb |
Querying for one element on an array is exactly like query for a field
equality. You could read the MongoDB documentation here. So your query will
be:
new Query(Criteria.where("users.$id").is(new ObjectId(userId)))
|
Connecting from WSO2DSS to MongoDB, receiving error: java.lang.NoClassDefFoundError: com/mongodb/ServerAddres. |
The missing class looks like ServerAddress (I assume the missing "s" is a
copy-paste issue) which is in the MongoDB Java driver (mongo-java-driver).
Make sure mongo-java-driver-2.xx.jar is on the runtime classpath. Note
that the runtime classpath is not always the same as the compile time
classpath.
|
mongodb: java: How to update a field in MongoDB using expression with existing value |
At the moment, MongoDB doesn't allow you to update the value of a field
according to an existing value of a field. Which means, you can't do the
following SQL:
UPDATE foo SET field1 = field1 / 2;
In MongoDB, you will need to do this in your application, but be aware that
this is no longer an atomic operation as you need to read and then write.
|
NoSQLUnit MongoDB test: Spring Data MongoDB approach |
Jaranda,
Seems that your spring repository and nosqlunit are working on different
databases. Try to modify your spring configuration to use the same database
of nosqlunit.
<mongo:db-factory id="mongoDbFactory" mongo-ref="mongo" dbname="test"
/>
|
sorting tr elements with nested tables, hide nested tbody while sorting |
jsFiddle Demo
At first I'd like to say that it's clear you really put effort in finding a
solution on your own so it really made me want to help.
The problem is that if you hide parts of the element after it begins to be
dragged, the size isn't recalculated.
The solution is like in the code you've linked. You have to catch a more
preliminary event (like mousedown) and hide it before the dragging begins.
$('tr.draggable_item').mousedown(function() {
$(this).find("tbody").hide();
});
$('tr.draggable_item').mouseup(function() {
$(this).find("tbody").show();
});
|
tal:condition not performing condition check |
If your result.sum_adt_out attribute is a string, your test will fail.
Also note that <> has been deprecated in Python, use != instead to
test inequality. Your template, simplified and with calling float() on the
value first to ensure that it is numeric, then becomes:
<td style="text-align: right;" tal:define="sum_adt_out
python:float(result.sum_adt_out)">
<span tal:condition="sum_adt_out"
tal:content="python:'%.1f' %
(float(result.sum_cenmn)/sum_adt_out,)">currentindex</span>
<span tal:condition="not:sum_adt_out">0.0</span>
</td>
|
Throwing exception in if condition causes if condition to be ignored |
bool isRightType = true;
if(isRightType == false)
{
const string msg = "Für diesen Control-Typ wird die falsche
Basisklasse verwendet!";
throw new Exception(msg);
}
You're hardcoding isRightType to true, then immediately testing for false.
There's no execution path for the if statement to be true and execute.
|
Verify this condition with regular condition |
A regex is not a good tool to use for this. You can do all you need by
splitting and parsing the string: (see it run)
class Main
{
public static void main (String[] args) throws java.lang.Exception
{
String inputString = "1,4,6,22,88,105:22";
int min = 1;
int max = 105;
String[] splitString = inputString.split("[,:]");
for (String part : splitString)
{
int parsedInt = Integer.parseInt(part);
if (parsedInt < min || parsedInt > max)
throw new Exception("Invalid");
}
System.out.println("Yay it's ok!");
}
}
|
rspec expect condition OR condition |
I don't think it is possible.
I do think you are mistaken when you say that you would be testing
implementation, instead of intent in your example.
When you write a test, you test whether what comes out matches your
expectation.
Creating a user is something completely different than returning error
messages.
In my opinion it would be strange to say: when I do this, I expect this, or
that, or that, or that to happen.
In my opinion you should write one test, that tests whether a user is
created when you send the correct parameters, and another test that deals
with what happens when a user tries to send illegal parameters.
|
MapReduce, MongoDB and node-mongodb-native |
The reason why the reduce function is never called is due to you emitting a
single value for each key so there is no reason for the reduce function to
actually execute. Here is an example of how you trigger the reduce function
collection.insert([{group: 1, price:41}, {group: 1, price:22}, {group: 2,
price:12}], {w:1}, function(err, r) {
// String functions
var map = function() {
emit(this.group, this.price);
};
var reduce = function(key, values) {
return Array.sum(values);
};
collection.mapReduce(
map,
reduce,
{
query:{},
// sort: {'count': -1},
// limit: 10,
// jsMode: true,
// verbose: false,
out: { inline: 1 }
},
function(err, results) {
console.log("----------- 0")
console.dir(er
|
I have a query in mongodb and the reference key's are in hashmap list , I need to process a simple query using java in mongodb |
When you post code, it helps if you indent it, so it is more readable. As
I mentioned to you on another forum, you need to go back and review the
Java collection classes, since you have multiple usage errors in the above
code.
Here are a few things you need to do to clean up your code:
1) You don't need to use the itkey iterator. Instead, use:
for (String key : likey)
and get rid of all the itkey.next calls. Your current code only processes
every second element of the List. The other ones are printed out.
2) Your HashMap will map a key to a Boolean. Is that what you want? You
said you want to count the number of non-zero values for the key. So, the
line:
Boolean listone = table.distinct(keys).contains(nullvalue);
is almost certainly in error.
3) When you iterate over the Ha
|
Mongodb : find documents including references to sub-documents [node-mongodb-native] |
MongoDB doesn't support joins so you have to query for the User details
separately. If you're using node.js, Mongoose provides a populate feature
to help simplify this so you can do something like the following to pull in
the user details:
Files.find().populate('Users_id')
|
Condition for max character limit and on mininum character putting condition |
All credit to Jerry, for his answer:
^(?:(?![AEIOU])[A-Z]{2}|[A-Z]{3,10})$
Explanation:
^ = "start of string", and $ = "end of string". This is useful for
preventing false matches (e.g. a 10-character match from an 11 character
input, or "MR" matching in "AMRXYZ").
(?![AEIOU]) is a negative look-ahead for the characters A,E,I,O and U -
i.e. the regex will not match if the text contains a vowel. This is only
applied to the first half of the conditional "OR" (|) regex, so vowels are
still allowed in longer matches.
The rest is fairly obvious, based on what you've already demonstrated an
understanding about regex in your question above.
|
mySQL: Why is if(condition,then,'') != '' not the same as if(condition,then,0) != 0 |
One explanation is that you have some partner ids where the substring
starts with a 0.
In the first case, the query is doing an integer comparison. A string like
'0a' evaluates to "0" as an integer. This is equal to 0, so they are
filtered out.
In the second case, the query is doing a string comparison. A string like
'0a' is different from '', so these pass the filtering clause.
|
Translating MongoDB query to a MongoDB java driver query |
I haven't checked the syntax. Also I don't know if your query works or not
but here's my try.
//unwind
DBObject unwind = new BasicDBObject("$unwind", "$scorearray");
// Now the $group operation
DBObject groupFields = new BasicDBObject("player", "$player");
groupFields.put("venue", "$scorearray.venue"));
groupFields.put("score", "$scorearray.score"));
DBObject group = new BasicDBObject("$group", new
BasicDBObject("_id", groupFields));
//sort
DBObject sort = new BasicDBObject("$sort", new
BasicDBObject("_id.score":1));
//secondgroup
DBObject secondGroupFields = new BasicDBObject("_id",
"$_id.player")
secondGroupFields.put("maxScore", new
BasicDBObject("$last":"$_id.score"));
secondGroupFi
|
How to select some rows if one condition is true and others if another condition is true? |
The union should do just fine, for example for your first example (this
will work only if tables a, b and c have similar column order and types):
select a.* from a
left join b on a.id=b.id
where b.id=:MY_PARAMETER
UNION
select c.* from c where c.id=:Another_Parameter
and not exists(select a.* from a
left join b on a.id=b.id
where b.id=:MY_PARAMETER)
UNION
select b.* from b
where not exists
(select c.* from c where c.id=:Another_Parameter
and not exists(select a.* from a
left join b on a.id=b.id
where b.id=:MY_PARAMETER))
and not exists (select a.* from a
left join b on a.id=b.id
where b.id=:MY_PARAMETER)
In order to build more effective query, I need more specific example.
SELECT a.* FROM a
INNER JOIN b ON a.id = b.id
WHERE b.id = :MY_PARAMETER
UNION
SELECT a.* FROM a
INNER JOIN b ON
|
SQL query - get rows from a table based on one condition and through join table based on another condition |
I wouldn't use user_tags.user_id as part of the join condition. Just do
specify both conditions in the where clause to make your intent clearer.
But to answer your question, yes you would need to de-dupe tags with
DISTINCT if one tags.id can be associated to many user_tags.tag_id
SELECT DISTINCT tags.*
FROM tags
JOIN user_tags ON tags.id = user_tags.tag_id
WHERE user_tags.user_id = 2
OR user_tags.owner_id = 2
LIMIT 0,30
|