简体   繁体   中英

selecting count from table with sum of another table

I have two table order table and order_item table order item has a foreign key to order table called order_id

I want to select count order with status cancelled and having sum order_item.cbs > 0

order table                      order_item table

************************* ************************************** * id * date * status * * id * status * cbc * cbs * order_id * ************************* ************************************** * 1 * null * CANCELLED * * 11 * * 1 * 0 * 1 * ************************* ************************************** * 2 * null * DELIVERED * * 12 * * 0 * 0 * 1 * ************************* **************************************

if you're using JDBC you can just do:

    public int getOrderInfo(){
    Statement stmt = null;
    ResultSet results = null;
    int queryResult = 0;
    try(Connection connection = [your connection here]){
        stmt = connection.createStatement();
        results = stmt.executeQuery("SELECT COUNT('status') FROM order INNER JOIN order_item ON order.id = order_item.order_id WHERE order.status = 'CANCELLED';");
        while(results.next()){
            queryResult = results.getInt(1);
        }
    }catch(Exception e){
    e.printStackTrace();
    }
    return queryResult;
}

as it is just a SQL query you are submitting.

SELECT o.id, o.status, sum(oi.cbs)
FROM order o JOIN order_item oi ON o.id = oi.order_id
WHERE o.status = 'CANCELLED' AND oi.cbs > 0
GROUP BY o.id, o.status

Sorry if my syntax on your table names isn't perfect, but this should be all you need. Let me know if you are still having trouble. This may need to be in a subquery if it does not work now I can modify it.

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