I have are resultset based on this SELECT statement:
"SELECT ca.mem_no, me.mem_surname, me.mem_first_name, " +
"lcc.call_cat, ca.call_location, ca.caller_name, lsc.call_sub_cat, ca.call_id, " +
"call_date_start, ca.call_note_start, ca.call_date_end, ca.call_duration, lcs.call_status, " +
"lca.call_action, lcr.call_res, ca.call_note_res\n" +
"FROM tblCall ca\n" +
"INNER JOIN tlkpCallStatus lcs on lcs.callstatus_id = ca.callstatus_id\n" +
"INNER JOIN tlkpCallAction lca on lca.callaction_id = ca.callaction_id\n" +
"INNER JOIN tlkpCallResolution lcr on lcr.callres_id = ca.callres_id\n" +
"LEFT OUTER JOIN tlkpCallSubCategory lsc on lsc.callsubcat_id = ca.callsubcat_id\n" +
"INNER JOIN tlkpCallCategory lcc on lcc.call_cat_id = ca.call_cat_id\n" +
"LEFT OUTER JOIN tblMember me on me.mem_no = ca.mem_no\n" +
"INNER JOIN tblClient cl on cl.client_ident = me.client_ident\n" +
"WHERE me.client_ident = \'AVA\'" +
"AND ca.call_date_start BETWEEN '2017-02-01' AND '2017-02-28'\n" +
"ORDER BY date(ca.call_date_start);\n"
;
which will rst.next() to a speadsheet ... i realize i can get the count of rows by waiting for the processing to finish, however i need the row count prior to writing the report .. i am faced with writing another pre sql statement getting COUNT(*) based upon the same JOIN and WHERE conditions. But i don't want to have two copies of basically the one sql statement ..
Is there a way (JAVA, Sqlite3) i can "SELECT COUNT(*)" from the existing resultset? ... seems a waste to have to go and get them all again just to be able to count the rows. :)
There is a way to probe a JDBC ResultSet and find out how many records are in that result set. But, it might cause the entire result set to be read across the network. Therefore, I vote for just running a separate COUNT(*) query if you really need to find the count. From a network usage point of view, this is very cheap, because you are just asking for a single number to be sent across.
There is also a SQL solution here, which unfortunately is not available for SQLite, which does not support analytic functions (yet). You could use the following query:
SELECT
ca.mem_no,
me.mem_surname,
me.mem_first_name,
COUNT(*) OVER () AS total_record_count -- change here
...
FROM
That is, we can use COUNT as an analytic function to find the total record count at the same time as running the rest of your original query. Again, not available for SQLite, but might be an option for other databases.
Related
I have this query:
"select distinct d from Dance d " +
"inner join d.meisterschaftDances ms " +
"inner join ms.danceRegistrations dr " +
"inner join dr.user u " +
"where (u.id = :userId " +
"or d.user.id = :userId) " +
"AND ms.meisterschaft.open = FALSE " +
"order by ms.meisterschaft.organizer.id, " +
"d.discipline, d.age, d.category, " +
"d.class"
The logic would be perfect for me but as we know distinct is not so easy with order by.
I get the same dance several times because the inner join to meisterschaftDances can have several references.
Sadly I dont know how to rewrite my query in such a way that it is working. Can somebody show me an example which would work. Thanks
As it's stated in the hibernate documentation:
For JPQL and HQL, DISTINCT has two meanings:
It can be passed to the database so that duplicates are removed from a result set
It can be used to filter out the same parent entity references when join fetching a child collection
You are interested in the second case, so, you need to add the QueryHints.HINT_PASS_DISTINCT_THROUGH hint, like below:
List<Dance> dances = entityManager.createQuery(
"select distinct d " +
"from Dance d " +
"inner join d.meisterschaftDances ms ...", Dance.class)
.setHint( QueryHints.HINT_PASS_DISTINCT_THROUGH, false )
.getResultList();
P.S. But the above approach may be not workable in some hibernate versions due to bugs (See for example HHH-13517 and HHH-13280)
I'm using the SQL MAX on a field in my db called "Date_Created", essentially i use it to bring back the most recent record for a particular user. It works fine for all user records that have higher count than 1 but when a user only has one record SQL MAX does not return a record" Can anyone advise what i'm doing wrong ?
code:
"SELECT CP_Score.Credit_Score "
. "FROM CP_Score "
. "INNER JOIN phpro_users ON CP_Score.ID_No=phpro_users.ID_No "
. "WHERE phpro_users.User_ID = $userloggedin "
. " AND CP_Score.Date_Created = (SELECT MAX(CP_Score.Date_Created) "
. " FROM CP_Score)";
SELECT CP_Score.Credit_Score
FROM CP_Score
INNER JOIN phpro_users ON CP_Score.ID_No=phpro_users.ID_No
WHERE phpro_users.User_ID = $userloggedin
AND CP_Score.Date_Created = (SELECT MAX(cps2.Date_Created)
FROM CP_Score cps2
WHERE cps2.ID_No=phpro_users.ID_No)
If you are looking for one record, you can limit the result set to a single record. In ANSI/ISO standard syntax:
SELECT s.Credit_Score
FROM CP_Score s INNER JOIN
phpro_users u
ON s.ID_No = u.ID_No
WHERE u.User_ID = $userloggedin
ORDER BY Date_Created DESC
FETCH FIRST 1 ROW ONLY;
Some databases express the FETCH FIRST clause differently -- SELECT TOP (1) or LIMIT are common.
My UNION ALL statement is not returning what I hoped it would. I am putting products into a location (73) and taking them out of the same location. I would like to know how many are remaining in that location. I am trying to figure this out by adding the amount in and subtracting the amount out. I am storing my transactions in tblWarehouseTransfer.
I would like to have one line for each product with the total. What I am getting is one line with the sum of the amount put into the location and one line with the sum of the amount taken out (as a negative number).
I am using a list box to display the list of all my products.
Me.lstCutWipers.RowSource = "SELECT tblProducts.ProductID, tblProducts.ProductName, Sum(tblWarehouseTransfer.Qty) AS SumOfQty " _
& " FROM tblWarehouseTransfer INNER JOIN tblProducts ON tblWarehouseTransfer.ProductID = tblProducts.ProductID " _
& " GROUP BY tblProducts.Productid, tblProducts.ProductName, tblWarehouseTransfer.LocationTo " _
& " HAVING (((tblWarehouseTransfer.LocationTo) = 73)) " _
& " UNION ALL SELECT tblProducts.ProductID, tblProducts.ProductName, -Sum(tblWarehouseTransfer.Qty) AS SumOfQty " _
& " FROM tblWarehouseTransfer INNER JOIN tblProducts ON tblWarehouseTransfer.ProductID = tblProducts.ProductID " _
& " GROUP BY tblProducts.Productid, tblProducts.ProductName, tblWarehouseTransfer.LocationFrom " _
& " HAVING (((tblWarehouseTransfer.LocationFrom)= 73))"
Can someone help me to join the 'in' and the 'out' as one total.
This example joins two subqueries which allows your two different sums to be added together, whereas a UNION only lists rows of the two queries together.
One downside to having subqueries is that it cannot be fully edited in query Design View... it requires the SQL View to edit the whole thing. BUT, you could save each subquery separately and then join those queries together in a third query. Then you could edit each part separately in Design View.
Also notice that I changed the HAVING clause to a WHERE clause. WHERE clauses can be more efficient if you are applying criteria to source values before they are aggregated (i.e. grouped and summed). HAVING applies the criteria after aggregating the data. If the criteria involves aggregate expressions, then they must appear in HAVING clause.
By changing to a WHERE clause it also means that you don't have to group on that field. The difference in speed may be negligible and it should return the same information, but just not necessary since every row contributing to that query will only be for the value in the WHERE clause. Just be aware that if you change the query at all, you need to consider the proper clause to apply criteria.
EDIT: Changed to LEFT JOIN and handled NULL in TotalSum with call to nz().
SELECT ToQuery.ProductID, ToQuery.ProductName, (ToQuery.SumOfQty + nz(FromQuery.SumOfQty, 0.0)) As TotalSum
FROM
(SELECT tblProducts.ProductID, tblProducts.ProductName, Sum(tblWarehouseTransfer.Qty) AS SumOfQty
FROM tblWarehouseTransfer INNER JOIN tblProducts ON tblWarehouseTransfer.ProductID = tblProducts.ProductID
WHERE tblWarehouseTransfer.LocationTo = 73
GROUP BY tblProducts.Productid, tblProducts.ProductName) AS ToQuery
LEFT JOIN
(SELECT tblProducts.ProductID, tblProducts.ProductName, -Sum(tblWarehouseTransfer.Qty) AS SumOfQty
FROM tblWarehouseTransfer INNER JOIN tblProducts ON tblWarehouseTransfer.ProductID = tblProducts.ProductID
WHERE tblWarehouseTransfer.LocationFrom = 73
GROUP BY tblProducts.Productid, tblProducts.ProductName) AS FromQuery
ON ToQuery.ProductID = FromQuery.ProductID
To be complete, this assumes that ProductID is a primary key and that ProductName is unique to each ProductID. If that is not true, you will need to change the outer query ON expression to match ProductName values as well (i.e. add AND ToQuery.ProductName = FromQuery.ProductName).
So I'm curious if a nested SELECT can reference it's outer SELECT in order to compare values. I haven't been able to test or see many examples on this topic.
As an example, I'm trying to write a query to select all Clothes rows that has a tag (some number) that is within a given list and has the highest time that is prior to given time (which is total number of seconds). The query in question is below:
SELECT c FROM Clothes c WHERE c.tag IN :tagList
AND (c.timeOfSale = (SELECT MAX(n.timeOfSale) FROM Clothes k
WHERE (c.tag = k.tag) AND (k.timeOfSale) < (:time))) GROUP BY c.tag
Is the comparison c.tag = k.tag valid? If not, is there an alternative?
#Query("SELECT b FROM Business b WHERE b <> :currentBusiness "
+ "and exists "
+ "(Select i from InterestMaster i, BusinessInterest bI where bI.interestMaster = i and bI.business = b"
+ "and i in (:userInterests))")
Page<Business> getCommunityBusiness(#Param("currentBusiness") Business currentBusiness, #Param("userInterests") List<InterestMaster> userInterests,Pageable pageable);
I am using the above JPQL and its working fine. So yes nested query can access outer query.
Yes. They're called correlated queries, where the subquery is evaluated for each row of outer query.
I have a sqlite database and I need to perform some arithmetic in my sql to get the final amount. The thing is I am not certain how to go and achieve this, I'm pretty certain from what I've been reading its a subquery which I need to group by lineID (unique id in my db)
The fields I want to include in the calculation below are
el.material_cost1 * el.material_qty1
el.material_cost2 * el.material_qty2
el.material_cost3 * el.material_qty3
The query I currently have is below. It returns the value of my costs apart from the fields missing above. As I store the material costs individually, I can't work out how to do a subquery within my query to get the desired result.
SELECT sum(el.enquiry_cost1) + sum(el.enquiry_cost2) + sum(el.enquiry_cost3)
FROM estimate e
LEFT JOIN estimate_line el
ON e.estimateID=el.estimateID
WHERE e.projectID=7 AND el.optional='false'
Use of a LEFT JOIN instead of an [INNER] JOIN is pointless, as your WHERE condition filters out any rows that could have differed.
I think you're making this harder than it needs to be. In particular, nothing in your description makes me think you need a subquery. Instead, it looks like this query would be close to what you're after:
SELECT
sum(el.enquiry_cost1)
+ sum(el.enquiry_cost2)
+ sum(el.enquiry_cost3)
+ sum(el.material_cost1 * el.material_qty1)
+ sum(el.material_cost2 * el.material_qty2)
+ sum(el.material_cost3 * el.material_qty3)
AS total_costs,
FROM
estimate e
JOIN estimate_line el
ON e.estimateID = el.estimateID
WHERE e.projectID = 7 AND el.optional = 'false'