简体   繁体   中英

MySQL Sum() from derived column

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 "

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM