Group by似乎没有在union SQL查询中工作

时间:2015-01-02 21:39:40

标签: mysql sql

这是我的SQL查询:

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");

带分组的选择似乎不是分组。

1 个答案:

答案 0 :(得分:1)

如果要对这两个值求和,可以在单个查询中执行此操作。以下内容应按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;

以下所有数据:

  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';