我有一个ls_order的表下面有这些字段 订单负责人 sales_person_id 订单成交价 price 订单创建时间 created_time 我要根据created_time 计算出 当天,当周,当月,当天分别销售额,并根据sales_person_id 分组,我想用一条sql实现怎么编写sql
时间: 2024-02-10 10:11:02 浏览: 124
可以使用以下SQL语句:
```sql
SELECT
sales_person_id,
SUM(CASE
WHEN created_time >= DATE(NOW()) AND created_time < DATE(NOW()) + INTERVAL 1 DAY
THEN price
ELSE 0
END) AS daily_sales_amount,
SUM(CASE
WHEN YEARWEEK(created_time) = YEARWEEK(NOW())
THEN price
ELSE 0
END) AS weekly_sales_amount,
SUM(CASE
WHEN YEAR(created_time) = YEAR(NOW()) AND MONTH(created_time) = MONTH(NOW())
THEN price
ELSE 0
END) AS monthly_sales_amount,
SUM(CASE
WHEN created_time >= DATE(NOW()) AND created_time < DATE(NOW()) + INTERVAL 1 DAY
THEN price
WHEN YEARWEEK(created_time) = YEARWEEK(NOW())
THEN price
WHEN YEAR(created_time) = YEAR(NOW()) AND MONTH(created_time) = MONTH(NOW())
THEN price
ELSE 0
END) AS total_sales_amount
FROM
ls_order
GROUP BY
sales_person_id;
```
这个SQL语句将会按照销售人员对订单进行分组,并使用 `SUM` 聚合函数计算每天、每周、每月和总销售额。其中,`CASE` 语句用于根据 `created_time` 字段判断订单是否属于当天、当周、当月或总销售额,并将相应的销售额累加到对应的字段中。
阅读全文