每周报告的 SQL
Posted
技术标签:
【中文标题】每周报告的 SQL【英文标题】:SQL for weekly report 【发布时间】:2015-02-02 05:47:48 【问题描述】:我需要为销售业绩生成每周报告
-------------------------------------------------- -------- 用户 周一 周二 周三 周四 周五 周六 周日 总计 -------------------------------------------------- -------- 纳文 25 25 30 25 20 20 0 145 阿杰 15 35 20 25 20 20 0 135
我用的是经典的asp
例如:
Select username , salesdate , salesamt
from sales ......
group by username
【问题讨论】:
如果没有错,您正在寻找 条件聚合 逻辑 【参考方案1】:您可以将聚合函数(例如 SUM)与 CASE 条件相结合,以获得您想要的报告。
例如:
SELECT USERNAME,
SUM(CASE WHEN WEEKDAY(SALESDATE)=0 THEN SALESAMT ELSE 0 END) AS MON,
SUM(CASE WHEN WEEKDAY(SALESDATE)=1 THEN SALESAMT ELSE 0 END) AS TUE
FROM SALES
GROUP BY USERNAME;
【讨论】:
【参考方案2】:创建表测试
create table `test` (
`day` datetime ,
`val` int (11),
`user` varchar (768)
);
insert into `test` (`day`, `val`, `user`) values('2012-01-01 00:00:00','465',NULL);
insert into `test` (`day`, `val`, `user`) values('2012-01-02 00:00:00','896',NULL);
insert into `test` (`day`, `val`, `user`) values('2015-01-26 11:37:07','678','Ajay');
insert into `test` (`day`, `val`, `user`) values('2015-01-26 11:37:07','324','Naven ');
insert into `test` (`day`, `val`, `user`) values('2015-01-27 11:37:14','74','Ajay');
insert into `test` (`day`, `val`, `user`) values('2015-01-25 11:37:14','65','Naven ');
insert into `test` (`day`, `val`, `user`) values('2015-01-25 11:37:14','35','Ajay');
insert into `test` (`day`, `val`, `user`) values('2015-02-01 11:35:59','12','Naveen');
insert into `test` (`day`, `val`, `user`) values('2015-02-01 11:37:07','23','Ajay');
insert into `test` (`day`, `val`, `user`) values('2015-01-30 11:36:40','34','Naven ');
insert into `test` (`day`, `val`, `user`) values('2015-01-30 11:36:40','56','Naven ');
insert into `test` (`day`, `val`, `user`) values('2015-01-31 11:36:32','12','Ajay');
insert into `test` (`day`, `val`, `user`) values('2015-01-30 11:36:40','13','Ajay');
insert into `test` (`day`, `val`, `user`) values('2015-01-28 11:36:46','14','Naven ');
insert into `test` (`day`, `val`, `user`) values('2015-02-01 11:37:07','10','Pankaj');
insert into `test` (`day`, `val`, `user`) values('2015-02-01 11:37:07','10','Pankaj');
insert into `test` (`day`, `val`, `user`) values('2015-01-27 11:37:14','20','Naven ');
insert into `test` (`day`, `val`, `user`) values('2015-01-29 11:37:36','10','Naven ');
愿望查询下方
SELECT DAYOFWEEK(DAY) AS sr ,DATE_FORMAT(DAY, '%a') DAY, SUM(val),USER, DAY FROM test
WHERE DAY >= CURDATE() - INTERVAL DAYOFWEEK(CURDATE())+6 DAY
AND DAY < CURDATE() - INTERVAL DAYOFWEEK(CURDATE())-1 DAY
GROUP BY DAY,USER
ORDER BY sr;
【讨论】:
以上是关于每周报告的 SQL的主要内容,如果未能解决你的问题,请参考以下文章