我正在建立库存管理系统,目前我正致力于报告功能。我想查询在给定日期之前每天销售的产品总数。查询:
SELECT created_at as created_at, SUM(quantity) as product_sales
FROM sales_products
WHERE created_at > '2018-04-19'
GROUP BY created_at
ORDER BY created_at DESC
LIMIT 100;
输出:
"created_at" "product_sales"
"2018-05-01 09:41:51" "110"
"2018-05-01 09:41:11" "150"
"2018-05-01 09:40:57" "120"
"2018-04-29 16:25:50" "12"
"2018-04-25 11:54:26" "2385"
"2018-04-24 11:54:26" "2485"
"2018-04-23 11:54:26" "2278"
"2018-04-22 11:54:26" "2277"
"2018-04-21 11:54:26" "2330"
"2018-04-20 11:54:26" "2408"
"2018-04-19 11:54:26" "2425"
现在直到今天,我插入了更多的值,总和发生了我想要的方式。但是,时间戳略有不同的记录不会分组。我也尝试使用LEFT(created_at,10)来仅选择日期部分,但它不起作用。
有什么想法吗?
非常感谢你!
SELECT LEFT(created_at, 10) as created, SUM(quantity) as product_sales
FROM sales_products
WHERE created_at > '2018-04-19'
GROUP BY created_at
ORDER BY created_at DESC
LIMIT 100;
答案 0 :(得分:0)
要按天分组,请使用group by date(created_at)
:
select date(created_at) as day, sum(quantity) as product_sales
from sales_products
where created_at > '2018-04-19'
group by day
order by day desc
limit 100
date
函数从表达式中提取日期并丢弃一天中的时间,这可能会因您的记录而异。
答案 1 :(得分:0)
这应该有所帮助:
select cast(created_at as date) as Day, sum(quantity) as product_sales
from sales_products
where created_at > '2018-04-19'
group by Day
order by Day desc
limit 100