简体   繁体   中英

Group by does not appear to be working in union SQL query

Here is my SQL query:

SELECT SUM(subtotal) 
FROM (
  SELECT SUM(product_price * how_many_purchased) as subtotal 
  FROM $table_name 
  WHERE location_id ='$location' 
    AND created_at >= '$startDate' 
    AND created_at <= '$endDate'  
UNION ALL 
SELECT SUM(shipping_total) 
FROM $table_name 
WHERE location_id ='$location' 
  AND created_at >= '$startDate' 
  AND created_at <= '$endDate' 
GROUP BY order_id) as subtotal");

The select with group by does not appear to be grouping.

If you want to sum the two values, you can do this in a single query. The following should give the total value by order_id :

  SELECT SUM(shipping_total) + SUM(product_price * how_many_purchased) as subtotal
  FROM $table_name
  WHERE location_id ='$location' AND created_at >= '$startDate' AND created_at <= '$endDate'
  GROUP BY order_id;

The following for all the data:

  SELECT SUM(shipping_total) + SUM(product_price * how_many_purchased) as subtotal
  FROM $table_name
  WHERE location_id ='$location' AND created_at >= '$startDate' AND created_at <= '$endDate';

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