V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
MySQL 5.5 Community Server
MySQL 5.6 Community Server
Percona Configuration Wizard
XtraBackup 搭建主从复制
Great Sites on MySQL
Percona
MySQL Performance Blog
Severalnines
推荐管理工具
Sequel Pro
phpMyAdmin
推荐书目
MySQL Cookbook
MySQL 相关项目
MariaDB
Drizzle
参考文档
http://mysql-python.sourceforge.net/MySQLdb.html
jss
V2EX  ›  MySQL

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

  •  
  •   jss · 2020-05-12 13:54:57 +08:00 · 2154 次点击
    这是一个创建于 1416 天前的主题,其中的信息可能已经有所发展或是发生改变。

    根据商户 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;
    
    7 条回复    2020-05-14 18:53:21 +08:00
    asAnotherJack
        1
    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
        2
    jss  
    OP
       2020-05-12 16:40:18 +08:00
    jss
        3
    jss  
    OP
       2020-05-14 16:11:40 +08:00
    @asAnotherJack 还是这个表 根据商户 ID 分组,同时统计出 order_type = 1 消费数量和 order_type = 2 提现数量 怎么写?
    asAnotherJack
        4
    asAnotherJack  
       2020-05-14 16:44:20 +08:00
    @jss #3 消费数量指什么,次数吗? count(if(order_type = 1,1,null))
    jss
        5
    jss  
    OP
       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
        6
    asAnotherJack  
       2020-05-14 17:24:51 +08:00
    @jss #5 搜 count if sum if 网上有很多
    jss
        7
    jss  
    OP
       2020-05-14 18:53:21 +08:00 via iPhone
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   5042 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 36ms · UTC 09:46 · PVG 17:46 · LAX 02:46 · JFK 05:46
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.