I have a SQLite table content with following columns:
-----------------------------------------------
|id|book_name|chapter_nr|verse_nr|word_nr|word|
-----------------------------------------------
the sql query
select count(*) from content where book_name = 'John'
group by book_name, chapter_nr
in DB Browser returns 21 rows (which is the count of chapters)
the equivalent with ORMLite android:
long count = getHelper().getWordDao().queryBuilder()
.groupByRaw("book_name, chapter_nr")
.where()
.eq("book_name", book_name)
.countOf();
returns 828 rows (which is the count of verse numbers)
as far as I know the above code is translated to:
select count(*) from content
where book_name = 'John'
group by book_name, chapter_nr
result of this in DB Browser:
| count(*)
------------
1 | 828
2 | 430
3 | 653
...
21| 542
---------
21 Rows returned from: select count(*)...
so it seems to me that ORMLite returns the first row of the query as the result of countOf().
I've searched stackoverflow and google a lot. I found this question (and more interestingly the answer)
You can also count the number of rows in a custom query by calling the > countOf() method on the Where or QueryBuilder object.
// count the number of lines in this custom query
int numRows = dao.queryBuilder().where().eq("name", "Joe Smith").countOf();
this is (correct me if I'm wrong) exactly what I'm doing, but somehow I just get the wrong number of rows.
So... either I'm doing something wrong here or countOf() is not working the way it is supposed to.
Note: It's the same with groupBy instead of groupByRaw (according to ORMLite documentation joining groupBy's should work)
...
.groupBy("book_name")
.groupBy("chapter_nr")
.where(...)
.countOf()
EDIT: getWordDao returns from class Word:
#DatabaseTable(tableName = "content")
public class Word { ... }
returns 828 rows (which is the count of verse numbers)
This seems to be a limitation of the QueryBuilder.countOf() mechanism. It is expecting a single value and does not understand the addition of GROUP BY to the count query. You can tell that it doesn't because that method returns a single long.
If you want to extract the counts for each of the groups it looks like you will need to do a raw query check out the docs.
Related
I unsuccessfully attempted to leverage Java's DerivedQueries but cannot accomplish the required result so I have to manually write a SELECT Statement.
I want to display one single record in my UI. This should be the most recently generated record (which means it has the highest ID Number) associated with a category that we call "ASMS". In other words, look through all the rows that have ASMS#123, find the one that has the highest ID and then return the contents of one column cell.
ASMS: Entries are classified by 11 specific ASMS numbers.
ID: AutoGenerated
PPRECORD: New entries being inserted each day
I hope the image makes more sense.
//RETURN ONLY THE LATEST RECORD
//https://besterdev-api.apps.pcfepg3mi.gm.com/api/v1/pprecords/latest/{asmsnumber}
#RequestMapping("/pprecords/latest/{asmsNumber}")
public List<Optional<PriorityProgressEntity>> getLatestRecord(#PathVariable(value = "asmsNumber") String asmsNumber) {
List<Optional<PriorityProgressEntity>> asms_number = priorityprogressrepo.findFirst1ByAsmsNumber(asmsNumber);
return asms_number;}
The ReactJS FE makes an AXIOS.get and I can retrieve all the records associated with the ASMS, but I do not have the skill to display only JSON object that has the highest ID value. I'm happy to do this in the FE also.
I tried Derived Queries. .findFirst1ByAsmsNumber(asmsNumber) does not consider the highest ID number.
Try this:
SELECT pprecord FROM YourTable WHERE id =
(SELECT MAX(id) FROM YourTable WHERE asms = '188660')
Explanation:
First line select pprecord, second line select the id
I'll improve the answer if any additional question. Upvotes and acceptions are appreciated~
To implement a pagination on a list, I need to do two queries:
Get elements count from selected table using SELECT COUNT(*)...
Get subset of list using LIMIT and OFFSET in a query.
Are there any way to avoid this?. Are There any metadata where this is stored?
The function resultSet.getRow() retrive the array index of list, then I need to make a query whose results are all rows. After I get a subSet but this is expensive so.
I want send a only query with limits and offsets and retrive the selected datas and total count of datas.
is this possible?
Thanks in advance,
Juan
I saw some things about this, then new doubts are coming on to me.
When a query is lanched with limits, we can add SQL_CALC_FOUND_ROWS * on "select" section as follow:
"SELECT SQL_CALC_FOUND_ROWS * FROM ... LIMIT 0,10"
After, I query the follow:
"SELECT FOUND_ROWS()"
I understand that first query store count in a internal var whose value will be returned on second query. The second query isn't a "select count(*) ..." query so "SELECT FOUND_ROWS()" query should be inexpensive.
Am I right?
Some test that I have made show the follow:
--fist select count(*), second select with limits--
Test 1: 194 ms
out: {"total":94607,"list":["2 - 1397199600000","2 - 1397286000000","13 - 1398150000000","13 - 1398236400000","13 - 1398322800000","13 - 1398409200000","13 - 1398495600000","14 - 1398150000000","14 - 1398236400000","14 - 1398322800000"]}
--the new way--
Test 2: 555 ms
out: {"total":94607,"list":["2 - 1397199600000","2 - 1397286000000","13 - 1398150000000","13 - 1398236400000","13 - 1398322800000","13 - 1398409200000","13 - 1398495600000","14 - 1398150000000","14 - 1398236400000","14 - 1398322800000"]}
Why the test dont show the expected result?
My assumptions are wrong?
thanks, regards
I have resolve the question
The next link has got the response.
https://www.percona.com/blog/2007/08/28/to-sql_calc_found_rows-or-not-to-sql_calc_found_rows/
One of our clients have requested information about customers.
I have written the query below, to extract the list of customers.
select * from customer;
Id | Name | Status
----+----------+-----------
1 Azam 0
2 Kapil 1
3 Osama 2
But the issue is the "Status" column, which is an enum from the java code(We have used hibernate for ORM).
Therefore, it is stored in the database as digits. The problem is, I have to replace the digits in the "Status"
column with constants before sending it to the customer, since the customer does not understand digits. I do this
by generating an excel file of the result set and amending the Status column values.
E.x.
In the Status column:
0 means Prospect, 1 means Active and 2 means Existing.
Question:
Is there a way to modify the result set returned from a query to obtain the following from Oracle alone:
select * from customer;
Id | Name | Status
----+----------+------------
1 Azam Prospect
2 Kapil Active
3 Osama Existing
I think you can use the decode function in the following way:
select id,name,decode(status,0,'Prospect',1,'Active',2,'Existing) from customer;
Regards
Giova
If you have a table containing the status details, then it should just be a matter of joining to that table and outputting the status description.
If you don't, and you know the status numbers/description won't change, then you could use a case statement:
select id, name, case when status = 0 then 'Prospect'
when status = 1 then 'Active'
when status = 2 then 'Existing'
...
else null -- can be omitted if null is the desired default, or change the null to the output required
end status
from customer;
In addition to other answers, if you want to store string values of Enum constants in the database, use this mapping
#Enumerated(value=EnumType.STRING)
private MyEnum myEnum;
I'm having some trouble here to create an appropriate SQL query. Any help will be much appreciated!
Some background:
I have the following entities
Equipment
id
nickname
owner_indicator
{...}
EquipmentGroup_Equipment
equipment_id
equipment_group_id
EquipmentGroup
id
name
description
I need to do a SQL / JPA Hibernate query that returns me:
EquipmentGroup.name, EquipmentGroup.description, Equipment.owner_indicator
And this will be grouped by EquipmentGroup.id, so if I have 10 equipments inside the group it will return information grouped by the EquipmentGroup.
The thing is, when I have for example more than one owner_indicator inside a EquipmentGroup it will return 2 rows. This is SQL 101. But i must return only one line with a blank text instead of the Owner Indicator.
What is the easiest way to do this ? I'd be glad to have the answer in SQL, but much more than glad to have it in Criteria JPA, heh.
If it does matter, I'm using Oracle 12c.
Thanks!
EDIT
As requested, here is some data:
Equipment
id nickname owner_indicator
1 EQP01 'V'
2 EQP02 'T'
EquipmentGroup_Equipment
equipment_group_id equipment_id
1 1
1 2
EquipmentGroup
id name description
1 GRP1 Group 1
My wanted resultSet is:
Result
EquipmentGroup.name EquipmentGroup.description, Equipment.owner_indicator
GRP1 Group 1 (empty string)
That empty string would be returned because I don't want 2 rows, like
Result
EquipmentGroup.name EquipmentGroup.description, Equipment.owner_indicator
GRP1 Group 1 'T'
GRP1 Group 1 'V'
If anything more than that is needed please advise.
Thanks!
I thin k you must to use a main query on EquipmentGroup and a subquery about return data on Equipment.
If you have more than 1 equipment rows about one group you must return DISTINCT empty; if you have 1 row returns owner_indicator otherwise you can return 'None'
Try this:
SELECT DISTINCT eg.name, eg.description,
(SELECT
CASE
WHEN count(e.id) > 1 THEN DISTINCT 'EMPTY'
WHEN count(e.id) = 1 THEN e.owner_indicator
ELSE 'none'
END
FROM Equipment e
WHERE e.equipmentGroup.id = eg.id)
FROM EquipmentGroup eg
I am using Lucene. I have three columns which are
DocId - TermID - TermFrequency
1 - 004 - 667
2 - 005 - 558
If i use mysql then query for AND operation is
SELECT * FROM table_name WHERE DocId='1' AND TermId='004'
How can i write above query in Lucene using JAVA. For one column search code i am using is
Query query = new QueryParser(Version.LUCENE_35,"TermID", analyzer).parse("004");
How can i use AND operation in QueryParser ??
Terms can be grouped with the AND keyword like so:
Query query = new QueryParser(Version.LUCENE_35,"TermID", analyzer).parse("004 AND DocId:1");
Note that you don't need to qualify the field for your "004" term because you've set "TermId" as the default field.
You should read the manual on the query syntax...it's pretty expressive.