mysql - SQL:有条件 SUM

标签 mysql sql laravel eloquent

我构建了一个查询来比较一家公司与其他公司的销售统计数据。

简化的,就像:

SELECT SUM(CASE WHEN company=foobar THEN sales ELSE 0) as sales_foobar,
SUM(sales) as sales_total, country, year, product FROM sales_table
GROUP BY country, year, product HAVING (the above sum again) > 0

合规性规则要求只能显示公司有销售的行,虽然我的代码会丢弃 foobar 没有销售的行,但由于订单和退款相等,它也会删除销售额为 0 的行。

现在,我怎样才能只获取公司有销售数据的行?

最佳答案

您可以在 HAVING 子句中计算与公司匹配的行数:

SELECT SUM(CASE WHEN company = foobar THEN sales ELSE 0 END) as sales_foobar,
       SUM(sales) as sales_total, country, year, product
FROM sales_table
GROUP BY country, year, product
HAVING SUM( company = foobar ) > 0;  -- there is at least one record for the company

关于mysql - SQL:有条件 SUM,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52084807/

相关文章:

PHP语法问题

mysql - 有两个条件的两个字段的选择

Python,SQLAlchemy,如何只用一个提交指令以有效的方式插入查询

mysql - 如何创建一个触发器,在更新表中的列之前将整个旧行保存到新表中?

mysql - com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException : Unknown column in 'field list' using Criteria and mapping annotation

php - 显示每个月的数据

mysql - SQLite:连接两个表中的选定列

android - 在 Android SQLite 中处理日期的最佳方式

php - 我如何在 Laravel 中过滤集合?

php - 如何在 laravel 迁移文件中使用多个数据库模式?