基于SALESS表,如何修改SQL查询生成目标销售分析报表?
嘿,咱们先理清楚你的需求~ 首先把你的数据库基础信息和当前查询整理出来:
你的数据库配置与当前查询
表创建与测试数据插入语句:
CREATE TABLE SALESS (id int, product int, salesdate DATETIME, amount float) INSERT INTO SALESS VALUES (1, 1, '2020-10-10', 500), (1, 1, '2020-11-10', 300), (1, 1, '2020-12-10', 200), (1, 2, '2020-10-10', 300), (1, 2, '2020-11-10', 1000), (1, 2, '2020-12-10', 200)
你当前使用的查询语句:
select product, year(salesdate) 'year', month(salesdate) 'month', sum(amount) 'total amount' from SALESS group by product, year(salesdate), month(salesdate) order by product, year(salesdate), month(salesdate)
这个查询会返回按产品、年份、月份分组的明细销售额清单,不过你提到需要「指定格式的目标结果」,虽然没明确说具体样式,但我猜大概率是想要把月份转成列的透视表样式(比如每个产品一行,直接看到10/11/12月的销售额),下面给你两种常见的修改方案:
方案1:通用条件聚合(适配绝大多数数据库)
这种写法兼容性极强,MySQL、SQL Server、PostgreSQL都能直接用:
select product, year(salesdate) as `year`, sum(case when month(salesdate) = 10 then amount else 0 end) as `Oct_amount`, sum(case when month(salesdate) = 11 then amount else 0 end) as `Nov_amount`, sum(case when month(salesdate) = 12 then amount else 0 end) as `Dec_amount`, sum(amount) as `year_total` -- 可选:增加年度总销售额汇总 from SALESS group by product, year(salesdate) order by product, year(salesdate)
执行后会把每个产品的各月销售额拆成单独列,数据展示更直观。
方案2:数据库专属透视函数(以SQL Server为例)
如果你的数据库是SQL Server,可以用PIVOT函数简化写法:
select product, [year], [10] as Oct_amount, [11] as Nov_amount, [12] as Dec_amount from ( -- 先整理基础数据为子查询 select product, year(salesdate) as [year], month(salesdate) as [month], amount from SALESS ) as src pivot ( sum(amount) -- 要聚合的字段 for [month] in ([10], [11], [12]) -- 要转成列的月份值 ) as pvt order by product, [year]
要是你用的是MySQL 8.0+或者PostgreSQL,也有对应的动态列/交叉表实现方式,不过静态列的写法对新手更友好~
当然啦,如果你的目标格式不是透视表(比如想要按产品合并行展示连续月份销售额、或者特定日期格式展示等),可以补充说明具体的目标结果样式,我再帮你调整查询语句~
内容的提问来源于stack exchange,提问作者Learner1111
相关产品推荐
相关产品推荐

