[请教] 同一张表根据指定 key 分组,并执行双重统计

2020-05-12 13:54:57 +08:00
 jss

根据商户 ID 分组,同时统计出order_type = 1消费金额moneyorder_type = 2提现金额money

表结构
DROP TABLE IF EXISTS `store_money_record`;
CREATE TABLE `store_money_record` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `order_no` char(40) NOT NULL,
  `store_id` int(11) NOT NULL DEFAULT '0',
  `money` decimal(10,2) DEFAULT '0.00',
  `content` char(60) NOT NULL,
  `type` tinyint(1) NOT NULL DEFAULT '0',
  `order_id` int(11) DEFAULT '0',
  `order_type` tinyint(1) DEFAULT '0',
  `create_time` int(11) DEFAULT NULL,
  `update_time` int(11) DEFAULT NULL,
  `delete_time` int(11) DEFAULT NULL,
  PRIMARY KEY (`id`),
  UNIQUE KEY `order_no` (`order_no`),
  KEY `idx_delete_time` (`delete_time`),
  KEY `idx_store_id` (`store_id`)
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8;
2182 次点击
所在节点    MySQL
7 条回复
asAnotherJack
2020-05-12 14:25:19 +08:00
select store_id, sum(if(order_type=1,money,0)) as money1, sum(if(order_type=2,money,0)) as money2 from store_money_record group by store_id
jss
2020-05-12 16:40:18 +08:00
jss
2020-05-14 16:11:40 +08:00
@asAnotherJack 还是这个表 根据商户 ID 分组,同时统计出 order_type = 1 消费数量和 order_type = 2 提现数量 怎么写?
asAnotherJack
2020-05-14 16:44:20 +08:00
@jss #3 消费数量指什么,次数吗? count(if(order_type = 1,1,null))
jss
2020-05-14 17:11:03 +08:00
@asAnotherJack 我没查到这块文档,一直搞不搞懂 sum(if(order_type=1,money,0)) 中 if 里的参数 含义; 那个 0 /null 在什么使用? 因为,我之前进行 count(if(order_type = 1,1,0)) 时,查询结果不正确 ,将 0 改成 null 就对了。
asAnotherJack
2020-05-14 17:24:51 +08:00
@jss #5 搜 count if sum if 网上有很多
jss
2020-05-14 18:53:21 +08:00

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/670898

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX