I have a table with scores that contestants get after the complete a quiz. I then select the max(points) for each user and i group by user
select distinct userName, max(points) as numpoints
from tblscore
group by userName
order by numpoints desc
this gives me the order of all the highest scores for the user. i want to store these records in an array and process it, i want to rank each record plus i want to display records where the users have a tie. How can this be achieved? how will the array be set up and processed to cater for this.
Create a class (e.g. UserScore) with two fields - username and points
Get the ResultSet for the desired query (via a Statement)
Define a List<UserScore> list = new ArrayList<UserScore>
Loop the result set, using while (rs.next()) and on each iteration create a new instance of the UserScore class, set both of its fields (e.g. userScore.setPoints(rs.getInt("numpoints")), and then add the object to the list
If you can do with a List - go with it. If you really need an array - use list.toArray(..)
Alternatively, you can use apache commons-dbutils, and after you create the UserScore class, you just call:
List<UserScore> list = new BeanListHandler(UserScore.class).handle(resultSet);
Note that in this case your fields should be called the same way as your returned column names/aliases. You can also use the ArrayListHandler, which, instead of a list of the defined class, will give you a List<Object[]> where each column will be an element in the array.
Related
I am creating an agent based model in Anylogic 8.7. There is a point that I want to use query to get a List of values from a database table(rs_table) with a condition, here is the Java code that anylogic writes at the designated place:
(int) selectFrom(rs_table) .where(rs_table.tr.eq(1)) .list(rs_table.impact)
but I do not know how to store those values and how to reach them one by one. I would be grateful if you help me out thanks.
I would use a collection. Add a collection element from the "Agent" Pallet. The collection should have the following properties:
Collection Class: LinkedList
Element Class: Int
Use the following code:
collection.addAll(
selectFrom(rs_table) .where(rs_table.tr.eq(1)) .list(rs_table.impact)
);
Now, you can access the value from the collection as follows:
collection.get(i);
The "Iterate over returned rows and do something" option of the Insert Database Query wizard is precisely designed for this. It produces query code that loops through the returned list and prints each column's value to the console (via a traceln call); you just replace the code within the loop with what you actually want to do for each returned row (where the template code shows you how to get the value of each column in the row).
The wizard (if you use the QueryDSL form) will produce code like below:
List<Tuple> rows = selectFrom(rs_table)
.where(rs_table.tr.eq(1))
.list();
for (Tuple row : rows) {
traceln(
row.get( rs_table.tr ) + "\t" +
row.get( rs_table.impact )
);
}
(with extra row.get lines for any other table columns beyond the tr and impact ones).
(In Java terms, the query's list function returns a List of Tuple objects as the code shows.)
I'm trying to make a query to get certain objects. The thing is.. I don't know how to make a query to get object that match an array. The User can be a member of multiple Groups, so the names of these groups are stored in User.groups as an array. I am trying to get all the objects of the class 'Group' that the current user is a member of. I came up with this:
ParseQuery query1 = ParseQuery.getQuery("_User"); //selects User Class
query1.whereEqualTo("username", current_user.toString()); //selects current user
query1.include("groups"); //include 'groups' of type array with names of the groups that the user is a member of
ParseQuery query2 = ParseQuery.getQuery("Group"); //select Groups Class
query2.whereContainedIn("group_name", ?); //<-- Get objects where group_name matches a value in the User.groups
The last line of code is obviously not the way to do it. I already looked at the Parse Guide! Help is much appreciated!
After some digging and testing I came up with a solution. It wasn't that difficult actually..
ParseQuery<ParseObject> groupQuery = new ParseQuery<ParseObject> ("Group");
groupQuery.include("array");
groupQuery.whereEqualTo("array", ParseUser.getCurrentUser().getUsername());
This code selects the class 'Group' which has an array with all the usernames in it called 'members' that looks like: ["user1","user2",".."]. This array is included. The last line of code selects all the objects that the user is a member of.
I am getting a list (initial list) from the session which contains the customer Ids in the below order:-
[208700013, 30216118005, 30616118005, 10121005444, 206700013]
Now I am passing these customerIds to the customer table as a collection using "IN" query for which I am getting a list of customerIds in string along with the other values.
But the customerIds are being retrieved in the following order:
10121005444
206700013
208700013
30216118005
30616118005
This is creating a problem when I display the values in the view.
How I can get the same order which is set in the initial list as supposed to the list order returned by the query?
If you only have a hand full of result sets, it might be easiest to sort them in java, using a Comparator.
If you have to do it in oracle you can use a statement like the following:
select * // never do that in production
from someTable
where id in (10121005444, 206700013, 208700013, 30216118005, 30616118005)
order by decode(id, 10121005444, 1, 206700013, 2, 208700013, 3, 30216118005, 4, 30616118005, 5)
You can't specify the order using the IN clause. I think you have two options:
perform the query using IN, and sort your result set upon receipt
issue a separate query for each specified id in order. This is obviously less efficient but a trivial implementation.
you can use this query --
SELECT id FROM table
WHERE id in (10121005444, 206700013, 208700013, 30216118005, 30616118005)
ORDER BY FIND_IN_SET(id,
"10121005444, 206700013, 208700013, 30216118005, 30616118005");
second list define the order in which you want your result set to be
I have a table , say A ; now in A i have attribute ID as string and Time as DateTime.
Now the condition is that different entries to the table can have same ID and they have to be clubbed together and further do some refinement on it.
I am using java, I write the SQL query that
Select * from A group by ID;
Now i get this data in a huge list in java. Now what i do is
Set_ID=NULL;
for(each element in List)
{
if(Set_ID equals elements `ID` from table)
Add the element to the same list
else
Create new List and add element to the list. Change Set_ID to current `ID`
}
This way i get all the Entries with same Id in different lists and i can process further.
But is this the efficient way to this; comparing strings for each element.
Any change i can make, to make it better. Thanks.
Instead of reading all the data into a list & then processing it into sub lists, I'd process them directly into sub lists as you pull them from the database
While inserting from spreadsheet to database I have rows which are already existed.so i need to check existed rows before inserting. I am doing it in Java.
In the spread sheet I have:
name
a
b
c
d
b
Database dbo.emp has:
name id
x 1
y 2
z 3
d 4
where the row is repeated. To find out the repeated row I need to search the arraylist. so i query both excel and sql database. I put result obtained by querying the Excel sheet into arraylist namexcel. And result obtained by querying dbo.emp into arraylist namedb.
Now I need to search which are the existed rows from binary search.
I wrote query and stored like this:
String ExcelQueryString2 = "select * from [Sheet1$]";
ResultSet SpreadsheetValues = stmt2.executeQuery(ExcelQueryString2);
List namexcel = new ArrayList();
while (SpreadsheetValues.next()) {
namexcel.add(SpreadsheetValues.getString("name"));}
String Querystring="SELECT Name from dbo.emp"
List namedb = new ArrayList();
ResultSet rs = statement.executeQuery(Querystring);
while(rs.next())
{
namedb .add(rs.getString("Name"));
}
My questions:
How do I implement binary search for these arraylist?
How do I omit this row before insertion?
How do I remove the duplicate row which is existed in exceldatabase?
Please provide me the code snippets.
binary search requires you to maintain the ArrayList sorted, and use Collections.binarySearch() for searching.
You might want to concider using a Set instead - which guarantees no duplicates as part of its behavior
You can consider using a LinkedHashSet, which ensures that no data is duplicated when data is added to it, whilst maintaining insertion order.
You can create set implementation using both lists currently you have. Then you can use set difference method approach used in this link.
http://www.java2s.com/Code/Java/Collections-Data-Structure/Setoperationsunionintersectiondifferencesymmetricdifferenceissubsetissuperset.htm
Actually you don't need go for a binary search. Before pass your list in to the binary search function you need to sort it. Which is a costly operation.