我有一个简单的销售表,其中包含以下列和数据
表名称:销售
SALES_ID SALES_DATE SALES_PERSON SALES_TOTAL
1 2019-01-02 Jones 5236.6
2 2019-01-17 Jones 3324.26
3 2019-01-03 Jim 2257.25
4 2019-01-17 Jim 5232.21
5 2019-01-13 Josh 3254.2
6 2019-01-15 Josh 215.36
现在我的问题是,假设今天是2019年1月17日,如何使用单个查询字符串得出低于结果的结果?
`SALES_PERSON`, `TODAY_SALES`, `MONTH_TO_DATE_SALES`
Jones 3324.26 8560.86
Jim 5232.21 7489.46
Josh 0.00 3469.56
谢谢!
答案 0 :(得分:1)
我修改了@Siva查询字符串,这是满足我问题的最终查询。非常感谢!
SELECT
SALES_PERSON,
IFNULL( ( SELECT SUM( SALES_TOTAL ) FROM SALES WHERE SALES_DATE = '2019-01-17' AND SALES_PERSON = sal.SALES_PERSON ), 0 ) AS TODAY_SALES,
( SELECT SUM( SALES_TOTAL ) FROM SALES WHERE MONTH ( SALES_DATE ) = '01' AND SALES_PERSON = sal.SALES_PERSON ) AS MONTH_TO_DATE_SALES
FROM
SALES AS sal
GROUP BY
SALES_PERSON
答案 1 :(得分:0)
使用子查询获取此结果
select SALES_PERSON,
IFNULL(( select SUM(SALES_TOTAL) from SALES where SALES_DATE = '2019-01-17' and SALES_PERSON = sal.SALES_PERSON ),0) as TODAY_SALES,
IFNULL(( select SUM(SALES_TOTAL) from SALES where MONTH(SALES_DATE)='01' and SALES_PERSON = sal.SALES_PERSON ),0) as MONTH_TO_DATE_SALES
from SALES as sal
group by SALES_PERSON
答案 2 :(得分:0)
您可以尝试执行子查询,然后对结果进行分组,以防万一您当天有不同的销售量而将其分组。
select sales_person,sum(today_sales),month_to_date
from
(SELECT a.sales_person,sum(a.sales_total) as today_sales,(select sum(sales_total)
from sales b
where year(b.sales_date)=year(a.sales_date) and month(b.sales_date)=month(a.sales_date)) as month_to_date
from sales as a
where a.sales_date=date(now())) c
group by sales_person,month_to_date
order by sales_person
答案 3 :(得分:0)
您可以将内部联接与子查询一起用于月份销售
select a.SALES_PERSON, a.SALES_TOTAL, t.month_total
from SALES a
inner join (
select SALES_PERSON, month(SALES_DATE) month, year(SALES_DATE) year, sum(SALES_TOTAL) month_total
from SALES
group by SALES_PERSON
) t ON t.SALES_PERSON = a.SALES_PERSON
AND t.month = month(curdate())
AND t.year = year(curdate())
WHERE a.SALES_DATE = curdate()