来自同一SQL查询的两个SUM

时间:2018-02-17 15:45:59

标签: php sql sorting sum

我有这个问题:

SELECT hour, SUM(field1+field2+field3) as product_total  
FROM db.dbf 
WHERE (product_ID BETWEEN 999 AND 9999) AND day IN ($date1,$date2) 
GROUP BY hour

查询有效并生成ID在999和9999之间的总产品。 结果如下:

hour     total_products
12:00    503
12:15    645
12:30    324
12:45    1268

我需要将一些products_ID与总SUM分开。因此,我有另一个问题:

SELECT hour, SUM(field1+field2+field3) as separated_total  
FROM db.dbf 
WHERE (product_ID BETWEEN 999 AND 1200 OR product_ID BETWEEN 6000 AND 7000) 
AND day IN ($date1,$date2) 
GROUP BY hour

我想要一个这样的结果:

hour     total_products   separated_products
12:00    503              63
12:15    645              53
12:30    324              120
12:45    1268             348

我希望我的数组看起来像这样:

array("hour" => $row['hour'], "products' => $row['product_total'], "separated_products" => $row['separated_total'])

我的问题是我正在使用一个巨大的表格,而且我正在使用两个单独的查询,这使得处理时间对我来说有点太长了。 如何将其变为一个更有效的查询?谢谢!

4 个答案:

答案 0 :(得分:0)

您应该可以使用UNION执行此操作,但我不知道如何在此处使用GROUP BY

SELECT hour, SUM(field1+field2+field3) as separated_total  
FROM db.dbf 
WHERE (product_ID BETWEEN 999 AND 1200 OR product_ID BETWEEN 6000 AND 7000) 
AND day IN ($date1,$date2) 
UNION 
SELECT hour, SUM(field1+field2+field3) as separated_products  
FROM db.dbf 
WHERE (product_ID BETWEEN 6000 AND 7000) 
AND day IN ($date1,$date2) 

答案 1 :(得分:0)

在PostgreSQL中,只需应用额外的过滤器。

SELECT
  hour,
  SUM(field1+field2+field3) AS total,
  SUM(field1+field2+field3) FILTER (
    WHERE product_ID BETWEEN 999 AND 1200
          OR product_ID BETWEEN 6000 AND 7000) as separated_total
FROM db.dbf 
WHERE day IN ($date1, $date2)
GROUP BY hour

其他一切都是CASE声明。

SELECT
  hour,
  SUM(field1+field2+field3) AS total,
  SUM(CASE WHEN product_ID BETWEEN 999 AND 1200
                OR product_ID BETWEEN 6000 AND 7000
           THEN field1+field2+field3
           ELSE 0
      END) AS separated_total
FROM db.dbf 
WHERE day IN ($date1, $date2)
GROUP BY hour

答案 2 :(得分:0)

只要您的位置包含两者,您就可以根据自己的条件获得两笔款项

SelECT hour, SUM(field1+field2+field3) as total1, sum(case when product_id between 6000 and 7000 then field1+field2+field3 else 0 end) total2  
FroM db.dbf 
WheRE (product_ID BETWEEN 999 AND 1200 OR product_ID BETWEEN 6000 AND 7000) 
And day IN ($date1,$date2) 
Group BY hour

答案 3 :(得分:0)

已经有多个答案,但我认为最简单的是:

SELECT hour, SUM(field1 + field2 + field3) as separated_total,
       SUM(CASE WHEN product_ID BETWEEN 999 AND 1200 OR
                     product_ID BETWEEN 6000 AND 7000
                THEN field1 + field2 + field3
                ELSE 0
           END) as separated_totl  
FROM db.dbf 
WHERE day IN ($date1, $date2) AND
      product_id BETWEEN 999 AND 9999
GROUP BY hour
ORDER BY hour;  -- in general, you should not assume the ordering of the results

这是有效的,因为您的特殊和是一般总和的子集,因此相同的WHERE子句有效。性能应与原始查询基本相同。

我还鼓励你使用参数,而不是使用日期常量之类的东西来查询字符串。