Sometime back I asked the question regarding how to do a Distinct query using Hibernate. Now that I'm past that milestone, there is another thing that I require. And that is, given the table,
---------------------------------------
| user_id | user_name | user_type |
---------------------------------------
| 1 | mark taylor | admin |
| 2 | bill paxton |co-ordinator|
| 1 | tony brooks | admin |
| 3 | ali jahan | developer |
---------------------------------------
I want to create a distinct query which returns the distinct user_type along with it's corresponding user_id. Please do note that the user_id for a particular user_type is same. So for example,
admin = 1
co-ordinator = 2
developer = 3
So the return I'm expecting is somewhat like a ArrayList or that sort which contains both values like
user_id,user_type
The code I've written to get Distinct UserType is as follows and I'm hoping there could be some modification to it to get the desired result.
public List<String> findDistinctUserName() throws HibernateException {
List<String> returnVal = new ArrayList<String>();
Criteria c = this.createCriteria();
c.setProjection(Projections.distinct(Projections.property("userType")));
c.addOrder(Order.asc("userType"));
List<String> userTypeList = c.list();
for(String userType : userTypeList) {
if(!userType.equalsIgnoreCase("")) {
returnVal.add(userType);
}
}
return returnVal;
}
Thank you for your answers in advance.
Try this:
criteria.setProjection(Projections.distinct(Projections.property("userType")), "userType");
Also u don't have to check for blank strings, try this:
criteria.add(Restrictions.ne("userType",""));
Related
I have a table which is something like this:
AccountNum
Name
RoutingNum
a1
name1
r1
a2
name2
r2
a2
name3
r1
I want to select all rows with a specific pair account number and routing number, for example :
input
List<accountNum, routingNumber> pairList = {<a1, r1>, <a2, r2>}
sql returns:
| AccountNum | Name | RoutingNum |
| -------- | -------------- |--------------
| a1 | name1 | r1 |
| a2 | name2 | r2 |
For some context I just want to make a single call, that I would be making using jdbc, this is my java code which only selects for account number, which is not what I want as I want to select using routingNum too:
String inSql = String.join(",", Collections.nCopies(plainAccountNumberEntries.size(), "?"));
List<String>accountNumberList = Arrays.asList("a1", "a2");
return ddsJdbc.query(
String.format("SELECT * from table where AccountNum in (%s)", inSql),
accountNumberList.toArray(),
new someMapper()
);
I want to avoid making multiple calls to the database for every entry in the list.
Thanks for your time.
Use an IN condition with multiple expressions in the list:
SELECT *
from table_name
where ( AccountNum, RoutingNum ) in ( ( 'A1', 'R1' ), ( 'A2', 'R2') )
My data at test.setName looks like this
| id | cities | lob |
|-------|---------------------|------------|
| id123 | ["Cthdcn","Ctdel"] | ["Lob132"] |
| id345 | ["Ctijs","Ctdelhi"] | ["LOB231"] |
| id765 | ["Cthui"] | ["Lob875"] |
"cities" is already present as LIST INDEX, and want to get a
particular record by specifying cities array like(["Ctijs","Ctdelhi"])
via java client.
I want to retrieve (get) records by specifying cities array using
java. I am using the following method
public Record testGet(String namespace, String set, String city, List<String> binNames) {
Statement statement = new Statement();
statement.setNamespace(namespace);
statement.setSetName(set);
Filter filter = Filter.contains("cities", IndexCollectionType.LIST, city);
statement.setFilter(filter);
RecordSet records = this.client.query((QueryPolicy)null, statement);
return records.getRecord();
}
I am getting null. How can I retrieve that specific record? (AQL version 3.23.0)
Here is small script in AQL in a text file, list.aql , to replicate your test:
list.aql:
TRUNCATE test
DROP INDEX test.setName idx_city
SELECT * FROM test
CREATE LIST INDEX idx_city ON test.setName (cities) STRING
INSERT INTO test.setName (PK, id, cities, lob) VALUES ('key1', 'id123', LIST('["Cthdcn", "Ctdel"]'), LIST('["Lob132
"]'))
INSERT INTO test.setName (PK, id, cities, lob) VALUES ('key2', 'id345', LIST('["Ctijs", "Ctdelhi"]'), LIST('["LOB23
1"]'))
INSERT INTO test.setName (PK, id, cities, lob) VALUES ('key3', 'id765', LIST('["Cthui"]'), LIST('["Lob875"]'))
select * from test.setName
select * from test.setName in LIST where cities = 'Cthdcn'
Output in aql:
aql> run 'list.aql'
TRUNCATE test
OK
DROP INDEX test.setName idx_city
Error: (201) Index does not exist on the system.
SELECT * FROM test
0 rows in set (0.156 secs)
OK
CREATE LIST INDEX idx_city ON test.setName (cities) STRING
OK, 1 index added.
INSERT INTO test.setName (PK, id, cities, lob) VALUES ('key1', 'id123', LIST('["Cthdcn", "Ctdel"]'), LIST('["Lob132"]'))
OK, 1 record affected.
INSERT INTO test.setName (PK, id, cities, lob) VALUES ('key2', 'id345', LIST('["Ctijs", "Ctdelhi"]'), LIST('["LOB231"]'))
OK, 1 record affected.
INSERT INTO test.setName (PK, id, cities, lob) VALUES ('key3', 'id765', LIST('["Cthui"]'), LIST('["Lob875"]'))
OK, 1 record affected.
select * from test.setName
+---------+------------------------------+--------------------+
| id | cities | lob |
+---------+------------------------------+--------------------+
| "id123" | LIST('["Cthdcn", "Ctdel"]') | LIST('["Lob132"]') |
| "id765" | LIST('["Cthui"]') | LIST('["Lob875"]') |
| "id345" | LIST('["Ctijs", "Ctdelhi"]') | LIST('["LOB231"]') |
+---------+------------------------------+--------------------+
3 rows in set (0.124 secs)
OK
select * from test.setName in LIST where cities = 'Cthdcn'
+---------+-----------------------------+--------------------+
| id | cities | lob |
+---------+-----------------------------+--------------------+
| "id123" | LIST('["Cthdcn", "Ctdel"]') | LIST('["Lob132"]') |
+---------+-----------------------------+--------------------+
1 row in set (0.001 secs)
OK
aql>
In Java, you will have to iterate through the recordset to get each record that satisfies the query.
RecordSet records = client.query( .....)
while (records.next()){
Record r = records.getRecord();
....
}
records.close()
I just tested the following code:
public void read () {
Record record = null;
Statement stmt = new Statement();
stmt.setSetName("setName");
stmt.setNamespace("test");
stmt.setIndexName("idx_city");
stmt.setFilter(Filter.contains("cities", IndexCollectionType.LIST, "Cthui"));
RecordSet recordSet = this.client.query(queryPolicy, stmt);
while (recordSet.next()) {
record = recordSet.getRecord();
System.out.println(record.toString());
}
}
and it worked for me.
$ java -jar ./target/dm-predicateFilter-1.0-full.jar
(gen:1),(exp:348432597),(bins:(id:id765),(cities:[Cthui]),(lob:[Lob875]))
I have two tables with a 1 to n relationship.
table hobbies has a foreign key to table users called "userid"
SELECT * FROM hobbies WHERE userid = 7
can have multiple results.
table users contains a list of user profile data and table hobbies contains a list of user hobbies. I want to print a list of profile info of multiple users with hobbies of each user. (hobbies concatenated into one String)
i currently have the following sql queries: (pseudocode):
ResultSet result = executeQuery("SELECT * FROM users;");
for each returned row: executeQuery("SELECT * FROM hobbies WHERE userid =" + result.getInt("ref"));
how do I get the SQL queries out of the loop to optimize performance with a big list of users?
I was trying to do a LEFT JOIN and then doing the WHERE ref= check in java instead of in SQL
problem is that I then get duplicate users and i only want to print one row for each user when processing the result set
also Im not sure if the JOIN is really an improvement in performance, because I have to process more rows.
table users
+--------+------+---------+--------+
| userid | name | country | telno |
+--------+------+---------+--------+
| 1 | John | USA | 123456 |
| 2 | Max | Germany | 345678 |
+--------+------+---------+--------+
+--------------+------------+
| userid |hobby |
+--------------+------------+
| 1 | football |
| 1 | basketball |
| 2 | TV |
| 2 | Music |
| 2 | football |
+--------------+------------+
example output:
John, USA, 123456, {football, basketball}
Max, Germany, 345678, {TV, Music, football}
This is most probably the fastest solution
SELECT name, country, telNo, GROUP_CONCAT(hobby)
FROM users u LEFT JOIN hobbies h ON u.id = h.userId
GROUP BY name, country, telNo
See https://dev.mysql.com/doc/refman/5.7/en/group-by-functions.html#function_group-concat for formatting options.
It's only good for the final output, e.g., if your hobbies contain commas, you wont't be able to parse them uniquely.
You can try :
SELECT h.userid, h.allyouneed FROM hobbies h, users u WHERE h.userid =u.userid
and get the info in one query
"SELECT * FROM hobbies h join users u on h.userid = u.userid WHERE userid = ?"
preparedStatement.setInt(result.getInt("ref"));
You can then save all the hobbies to a list similar to the 'Book' example below.
public static List<String> selectAll() throws SQLException {
PreparedStatement ps = null;
ResultSet rs = null;
// THE LIST OF BOOKS YOU WILL RETURN
List<String> books = new ArrayList<>();
String sql = "SELECT BOOK FROM BOOKs";
try(Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/bookshop", "root", "");){
ps = conn.prepareStatement(sql);
rs = ps.executeQuery();
while(rs.next()){
String book= rs.getString ("BOOK");
// ADD BOOK TO THE LIST
books.add(book);
}
}
finally{
ps.close();
rs.close();
}
// RETURN LIST OF ALL BOOKS
return books;
}
SELECT u.userid,u.name,u.country GROUP_CONCAT(hobby SEPARATOR ',')
FROM hobbies as h join users as u on h.userid=u.userid
where h.userid = ? GROUP BY u.userid,u.name,u.country;
assumming you have relationship on hobbies to users. the query will concat the columns of hobby of the join tables, and there will be one unique user per row.
I have a table with columns like this:
+--------+----+--------+---------------+------- +-------+---------+
| DATE | ID | Name | Cattle Type | Liter | Shift | Payment |
+--------+----+--------+---------------+------- +-------+---------+
And Data is like this
9-9-2016 | 01 | Abhi | Cow | 2 | AM | 50 |
9-9-2016 | 02 | Ram | Buff | 1 | AM | 25 |
9-9-2016 | 01 | Abhi | Buff | 2 | PM | 50 |
9-9-2016 | 01 | Abhi | Cow | 2 | PM | 50 |
I am fetching all the data by passing date in the database function
example :-
databaseObject.getAlldata(String From_date, StringTo_date)
After that i get all the values from my database and i store it to a list.
I need to have id without any duplicate. Actually I need their id and Cattle type,liter,payment What is the best Sqlite command to make this?
My desired result is something like this:
ID : 1
Cow = 4.00 Litre Rs 100
Buff = 2.00 Litre Rs 50
Total = Rs 150
ID : 2
Cow = 0.00 Litre Rs 0.0
Buff = 1.00 Litre Rs 25
Total = Rs 25
My code is :
list1 = db.getAllMilkCollection(start, end);
try {
for( i = 0; i < list1.size(); i++) {
CattleTypeCowTotal = 0;
CattleTypeBuffTotal = 0 ;
String id = list1.get(i).member_code;
list2 = db.getAllDataOfPaymentRegister(start,end,id);
for( j = 0; j < list2.size(); j++) {
String member_name = list2.get(j).member_name;
String Cattle_type = list2.get(j).cattle_type;
if(Cattle_type.equalsIgnoreCase("Cow")){
String amount = list2.get(j).amount.trim();
if(amount!=null){
CattleTypeCowTotal += Float.parseFloat(amount);
}
}
if(Cattle_type.equalsIgnoreCase("buff")){
String amount = list2.get(j).amount.trim();
if(amount != null){
CattleTypeBuffTotal += Float.parseFloat(amount);
}
}
}
System.out.println("xxxxxxxxxxxxxxxxxxxx");
}
} catch (Exception e) {
Log.e("Error", ""+e);
}
Thanks in advance :) :)
Considering you want to display the data categorized as per the ID showing sum of Quantity(Liter in your case) and sum of Payment for each cattle
1. Use the below query to get the data giving sum of quantity and sum of payment for each cattle categorized by ID
select ID, Cattle_type, sum(Liter) as Quantity, sum(Payment) as Total from ABC
where Date between "2016-09-09" and "2016-09-10"
group by Cattle_type, ID;
2. Create a model class and store the result of the above query into it.
3. Add the objects of model class into a ArrayList.
I think from here you can manage to display the data categorized by ID and get the total payment for each ID.
You can do like following:
Select ID, Name, Cattle_TYPE, SUM(Liter) as Quantity, SUM(payment) as Total
from Table_name
where date > from_date
and date < to_date
group by ID,Name,Cattle_TYPE
This will give you all records you want in proper format. Just add that to list and do wantever you want to do.
The SQLite DISTINCT keyword is used in conjunction with SELECT statement to eliminate all the duplicate records and fetching only unique records.
There may be a situation when you have multiple duplicate records in a table. While fetching such records, it makes more sense to fetch only unique records instead of fetching duplicate records.
For more information check the link
Cursor cursor = db.query(true, YOUR_TABLE_NAME, new String[] { COLUMN_NAME_1 ,COLUMN_NAME_2, COLUMN_NAME_3 }, null, null, COLUMN_NAME_2, null, null, null);
COLUMN_NAME_2 is the column on which data has to be distinct.
I have two db tables:
TARGET_TABLE (composite key on USER_ID and TARGET_ID)
USER_ID | TICKET_NO | TARGET_USER
---------------------------------
A11 | 12345 | A22
A11 | 12346 | A33
A44 | 12347 | A55
USER_DETAILS_TABLE
CORP_ID | USER_NAME
------------------
A11 | Steve
A22 | Jon
A33 | Paul
A44 | Dave
A55 | James
I want to be able to join these tables when I'm using select statements only.
For example I would like to do:
Select USER_ID, USER_NAME, TICKET_NO FROM TARGET_TABLE INNER JOIN USER_DETAILS ON TARGET_TABLE.USER_ID = USER_DETAILS_TABLE.CORP_ID
I can't seem to find the best way to do this. I have looked at the Hibernate examples for mapping but these are examples on how to write to both tables I simply want to get a user name from a table I can't touch!
I currently have two separate mappings for each table and run a separate query to get the user name but this doesn't seem like the best way to do it.
This HQL would work select tt.userId, tt.ticketNo, u.userName from TargetTable tt, User u where tt.userId = u.corpId.
However, this would return a List<Object[]> where each list element represents one row with 3 columns. You could extract these manually, or for example have some my.package.UserVO object with constructor public UserVO(String userId, String ticketNo, String userName) { ... }. In that case, this
session.createQuery("select new my.package.UserVO(tt.userId, tt.ticketNo, u.userName) from TargetTable tt, User u where tt.userId = u.corpId", UserVO.class).list()
would return instances of UserVO.