忽略 where 子句中的某些列 sql
ignore certain columns in where clause sql
我创建了一个测试数据库来尝试解决这个问题。我创建了一个销售 table,其中有一个金额,sale_made(销售完成时)和 table.I 中的项目描述,我试图通过仅使用一个 table 只是,我想得到所有商品整体售出的总和,整体售出的商品数量和销售商品总天数的一半。这是我的查询
select sum(amount) as 'total amount for all items sold'
,count(amount) as 'Total items sold',
count(sale_made)as 'half total days' from sales where sale_made BETWEEN "2018-07-02" and "2018-07-05" ;
查询正常,但 where 子句影响总金额(金额)和售出商品的数量。有没有办法让 where 子句不影响前两列?
我尝试过自行加入 table 并使用 table 别名,但这没有什么区别
您需要条件聚合:
select sum(amount) as `total amount for all items sold`,
count(amount) as `Total items sold`,
sum(sale_made between '2018-07-02' and '2018-07-05') as `half total days`
from sales;
备注:
- 单引号用于字符串和日期常量(ANSI 标准)。这就是为什么我将双引号更改为单引号。
- MySQL 使用反引号转义名称。我不喜欢需要引用的列别名,但你正在使用它们,所以我选择了反引号(双引号也可以)。
- MySQL 有一个方便的 shorthand 将布尔值视为数字上下文中的整数,“1”表示真,“0”表示假。因此,对第三列使用
sum()
。
我创建了一个测试数据库来尝试解决这个问题。我创建了一个销售 table,其中有一个金额,sale_made(销售完成时)和 table.I 中的项目描述,我试图通过仅使用一个 table 只是,我想得到所有商品整体售出的总和,整体售出的商品数量和销售商品总天数的一半。这是我的查询
select sum(amount) as 'total amount for all items sold'
,count(amount) as 'Total items sold',
count(sale_made)as 'half total days' from sales where sale_made BETWEEN "2018-07-02" and "2018-07-05" ;
查询正常,但 where 子句影响总金额(金额)和售出商品的数量。有没有办法让 where 子句不影响前两列?
我尝试过自行加入 table 并使用 table 别名,但这没有什么区别
您需要条件聚合:
select sum(amount) as `total amount for all items sold`,
count(amount) as `Total items sold`,
sum(sale_made between '2018-07-02' and '2018-07-05') as `half total days`
from sales;
备注:
- 单引号用于字符串和日期常量(ANSI 标准)。这就是为什么我将双引号更改为单引号。
- MySQL 使用反引号转义名称。我不喜欢需要引用的列别名,但你正在使用它们,所以我选择了反引号(双引号也可以)。
- MySQL 有一个方便的 shorthand 将布尔值视为数字上下文中的整数,“1”表示真,“0”表示假。因此,对第三列使用
sum()
。