MySQL Sum() from derived column - mysql

I am joining product and cart table to calculate for the total price for each cart. Here is my sql statement:
String sql = "SELECT p.productID, p.productName, p.productPrice, c.quantity, p.productPrice * c.quantity as new_unit_price, SUM(p.productPrice * c.quantity) AS totalPrice"
+ " FROM sm_product p INNER JOIN sm_cart c "
+ "ON p.productID = c.productID"
+ " WHERE c.custName = '" + custName + "'";
I derived a column named new_unit_price by multiplying the quantity from cart table and product price from product table. Then I want to use the derived column which is new_unit_price to sum up the price of all item in the cart. I get the data from the column in database by:
double subItemTotal = rs.getDouble("new_unit_price");
double totalPrice = rs.getDouble("totalPrice");
My new_unit_price works. But unfortunately, my sum does not works. It's still 0. Does anybody know how can I sum up the value from derived column? Thanks in advance.

To use the SUM() function, you'll need to do a GROUP BY at the end of your statement.
This should get your overall cart total:
String sql = "SELECT c.custname "
+ ", SUM(p.productPrice * c.quantity) AS totalPrice"
+ " FROM sm_product p INNER JOIN sm_cart c "
+ "ON p.productID = c.productID"
+ " AND c.custName = '" + custName + "'"
+ " GROUP BY c.custname;"
Also, I changed the WHERE to an AND so it is evaluated earlier and should make the query faster.
If you want the new_unit_price and the cart total in the same query, you have to go back into the tables again to get that data. Something like this should work:
String sql = "SELECT p.productID, p.productName, p.productPrice, c.quantity "
+ ", p.productPrice * c.quantity as new_unit_price, total.totalPrice FROM "
+ "( "
+ "SELECT c.custname "
+ ", SUM(p.productPrice * c.quantity) AS totalPrice"
+ " FROM sm_product p INNER JOIN sm_cart c "
+ "ON p.productID = c.productID"
+ " AND c.custName = '" + custName + "'"
+ " GROUP BY c.custname"
+ ") AS total "
+ "INNER JOIN sm_cart c "
+ "ON total.custname=c.custname "
+ "INNER JOIN sm_product p "
+ "ON p.productID = c.productID "

Related

Convert mysql query to jpa query with pagination supported

I have mysql query for joining 3 tables, how can i convert this into JPA with pagination supported.
query :
SELECT promotion.name,
promotion.promotion_type,
promotion.start_date,
promotion.end_date,
promotion_history.`count` AS order_count,
Count(user_promotion_history.promotionid) AS user_count
FROM promotion
INNER JOIN user_promotion_history
ON promotion.promotionid = user_promotion_history.promotionid
INNER JOIN promotion_history
ON promotion.promotionid = promotion_history.promotionid
WHERE promotion.status = "created"
GROUP BY promotion.name,
promotion.promotionid,
promotion.promotion_type,
promotion.start_date,
promotion.end_date,
order_count;
I have created all entity and repository classes and used native query,
#Query(value = "select promotion.name, promotion.promotion_type, promotion.start_date, promotion.end_date" +
" promotion_history.count as order_count, count(user_promotion_history.promotionid) as user_count" +
" from promotion" +
" inner JOIN user_promotion_history on" +
" promotion.promotionid = user_promotion_history.promotionid" +
" inner join promotion_history on" +
" promotion.promotionid = promotion_history.promotionid" +
" where promotion.status = :status" +
" group by" +
" promotion.name, promotion.promotionid, promotion.promotion_type, promotion.start_date,promotion.end_date, order_count",
nativeQuery = true)
List<Object[]> findByStatus(#Param("status")PromotionStatus status);
but getting an error like this.
You have an error in your SQL syntax; check the manual that
corresponds to your MySQL server version for the right syntax to use
near '.count as order_count, count(user_promotion_history.promotionid)
as user_count f' at line 1
For pagination i have used Pageable parameter.
#Query(value = "select promotion.name, promotion.promotion_type, promotion.start_date, promotion.end_date," +
" promotion_history.count as order_count, count(user_promotion_history.promotionid) as user_count" +
" from promotion" +
" join user_promotion_history on" +
" promotion.promotionid = user_promotion_history.promotionid" +
" join promotion_history on" +
" promotion.promotionid = promotion_history.promotionid" +
" where promotion.status = ?1" +
" group by" +
" promotion.name, promotion.promotionid, promotion.promotion_type, promotion.start_date,promotion.end_date, order_count \n-- #pageable\n",
nativeQuery = true)
List findByStatus(String status, Pageable pageable);
when i see query looks like this,
Hibernate: select promotion.name, promotion.promotion_type, promotion.start_date, promotion.end_date, promotion_history.count as order_count, count(user_promotion_history.promotionid) as user_count from promotion join user_promotion_history on promotion.promotionid = user_promotion_history.promotionid join promotion_history on promotion.promotionid = promotion_history.promotionid where promotion.status = ? group by promotion.name, promotion.promotionid, promotion.promotion_type, promotion.start_date,promotion.end_date, order_count
-- #pageable
order by join.user_count desc limit ?
error says : org.hibernate.engine.jdbc.spi.SqlExceptionHelper Unknown column 'join.user_count' in 'order clause'
somewhere "join." is getting added in order by clause.

Native JPA query and SQL query not giving the same result

I have 2 tables: one called issues and the other is time_entries which have id_issue as foreign key. I made an INNER JOIN based on the id_issue column.
SELECT
SUM(time_entries.hours)
, issues.id
, time_entries.created_on
, time_entries.updated_on
, issues.`estimated_hours`
, issues.`done_ratio`
FROM
issues
INNER JOIN
time_entries
ON
issues.id = time_entries.issue_id
WHERE
issues.project_id = 2
GROUP BY
issues.id
I put this query in a native query:
Query query = (Query) this.em.createNativeQuery(
"SELECT " +
" SUM(time_entries.hours) " +
" , issues.id " +
" , issues.estimated_hours" +
" , issues.done_ratio" +
"FROM " +
" issues " +
"INNER JOIN " +
" time_entries " +
"ON " +
" issues.id = time_entries.issue_id " +
"WHERE " +
" issues.project_id = 2 " +
"GROUP BY " +
" issues.id");
List<?> result = query.getResultList();
When i execute those 2 lines of Java code, I don't get the same result as executing this query in MySQL console but I got the same query in the trace.

syntax error (missing operator) in query expression sri.invoiceNo = sri.invoiceNo INNER JOIN Staff s oN s.Staffid = sr.userld

"SELECT SalesReturnId, ReturnDate, sr.InvoiceNo, (lastname & ', ' & firstname & ', ' & MI) as StaffName, TotalAmount, SUM(sri.Quantity) as TotalQuantity FROM SalesReturn sr INNER JOIN SalesReturnItem sri ON sr.InvoiceNo = sri.InvoiceNo INNER JOIN Staff s ON s.StaffId = sr.userID WHERE ReturnDate BETWEEN '" + startDate.ToString("yyyy-MM-dd") + "' AND '" + endDate.ToString("yyyy-MM-dd") + "' AND sr.InvoiceNo LIKE '%" + txtName.Text + "%' GROUP BY sr.InvoiceNo ORDER BY ReturnDate, sr.InvoiceNo DESC";
When I run that query I keep getting this error:
syntax error (missing operator) in query expression sri.invoiceNo =
sri.invoiceNo INNER JOIN Staff s oN s.Staffid = sr.userld
In Access you need parentheses when you have more than one join:
SELECT SalesReturnId, ReturnDate, sr.InvoiceNo,
(lastname & ', ' & firstname & ', ' & MI) as StaffName,
TotalAmount, SUM(sri.Quantity) as TotalQuantity
FROM (SalesReturn sr
INNER JOIN SalesReturnItem sri ON sr.InvoiceNo = sri.InvoiceNo )
INNER JOIN Staff s ON s.StaffId = sr.userID
WHERE ReturnDate BETWEEN '" + startDate.ToString("yyyy-MM-dd") + "' AND '" + endDate.ToString("yyyy-MM-dd") + "'
AND sr.InvoiceNo LIKE '%" + txtName.Text + "%'
GROUP BY sr.InvoiceNo
ORDER BY ReturnDate, sr.InvoiceNo DESC;

MySQL Temporary Table query - add calculated column to table calculated in select

I'm trying to make a temporary table from a query with another column which is calculated in the query...
Here is my query:
asprintf(&query,
"CREATE TEMPORARY TABLE IF NOT EXISTS task_tab (PRIMARY KEY(event_id))"
"SELECT V.id as event_id, V.event_time, D.user, V.location FROM device D "
"JOIN device_service DS ON D.id = DS.device_id "
"JOIN services S ON DS.service_id = S.id "
"JOIN device_event V ON D.id = V.device_id "
"WHERE V.store = 'event_box' AND S.options = 'box_length' AND (S.flags & 1 = 1)"
"AND V.event_time + (IF(S.value IS NULL, %d, S.value) * 86400000) <= %llu"
"AND D.id IN ( SELECT D.id FROM device D "
"JOIN device_service DS ON D.id = DS.device_id "
"JOIN services S ON DS.service_id = S.id "
"WHERE S.action = 'delete' AND (S.flags & 1 = 1)",
app_config->def_expire, current_epoch_ms);
I'd like to create a column 'expire_time' in this temporary table, and store the result of this part of the query in that column:
V.event_time + (IF(S.value IS NULL, %d, S.value) * 86400000)
Any ideas?
Add
V.event_time + (IF(S.value IS NULL, %d, S.value) * 86400000) AS `expire_time`
to your SELECT filed list

57, 57 An identification variable must be defined for a JOIN expression

I am getting the error
[57, 57] An identification variable must be defined for a JOIN expression
when trying to run this query
public String searchString = "test";
public List<Appointment> appointmentRangeSearch(Date startdatetime, Date endDate) {
Query q = em.createQuery("SELECT u FROM Appointment U INNER JOIN Users_appointment "
+ "ON u.userid = users_appointment.userid"
+ " WHERE u.startDatetime BETWEEN :date1 AND :date2 "
+ "AND u.ATTENDEES_USER_NAME LIKE :search");
//Query q = em.createQuery("SELECT u FROM Appointment U WHERE u.startDatetime BETWEEN :date1 AND :date2");
q.setParameter("search", "%" + searchString + "%");
q.setParameter("date1", startdatetime, TemporalType.TIMESTAMP);
q.setParameter("date2", endDate, TemporalType.TIMESTAMP);
return q.getResultList();
}
What is causing this? How can it be fixed?
Maybe, beacuse you have different table names:
INNER JOIN Users_appointment
AND
users_appointment.userid
Don't see anything wrong... try making U lower case and use
SELECT u.* FROM Appointment u....
em.createQuery("SELECT u.* FROM Appointment u INNER JOIN Users_appointment "
+ "ON u.userid = users_appointment.userid"
+ " WHERE u.startDatetime BETWEEN :date1 AND :date2 "
+ "AND u.ATTENDEES_USER_NAME LIKE :search");