HAVING SUM()问题

时间:2014-03-10 13:40:30

标签: sql

我想使用HAVING SUM()变量按日期添加总销售额,但是它没有按预期工作。

    SELECT
       sum(SalesA+SalesB) as Sales,
       sum(tax) as tax,
       count(distinct SalesID) as NumOfSales,
       Date
    FROM
       SalesTable
    WHERE
       Date >= '2014-03-01'
    GROUP BY
       Date, SalesA
    HAVING
       sum(SalesA+SalesB) >= 7000
    ORDER BY
       Date 

结果是;

   |Sales| tax | NumOfSales | Date |
    10224| 345 |     1      |2014-03-06| 
     9224| 245 |     1      |2014-03-06|
     7224| 145 |     1      |2014-03-06|

如果我在GROUP BY子句中删除SalesA,它似乎忽略了我的HAVING sum子句并添加了所有总数。

我希望结果按照这样的日期加总。

    |Sales| tax | NumOfSales | Date |
     26672| 735 |     3      |2014-03-06

感谢您提供任何帮助。

3 个答案:

答案 0 :(得分:2)

您可以尝试重写SQL语句,如下所示。

SELECT
   sum(SalesA+SalesB) as Sales,
   sum(tax) as tax,
   count(distinct SalesID) as NumOfSales,
   Date
FROM
   SalesTable
WHERE
   Date >= '2014-03-01' AND SalesA+SalesB >= 10000
GROUP BY
   Date
ORDER BY
   Date

答案 1 :(得分:1)

尝试使用HAVING Sales >= 7000

答案 2 :(得分:1)

是否要删除salesa + sales b< 7000,以便您只对总SalesA + SalesB> = 7000?

的行求和
SELECT
   sum(SalesA+SalesB) as Sales,
   sum(tax) as tax,
   count(distinct SalesID) as NumOfSales,
   Date
FROM
   SalesTable
WHERE
   Date >= '2014-03-01'
   and
   SalesA+SalesB >= 7000
GROUP BY
   Date
ORDER BY
   Date