› 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 · May 12, 2020 · 3387 views
    This topic created in 2333 days ago, the information mentioned may be changed or developed.

    根据商户 ID 分组,同时统计出order_type = 1消费金额money和order_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 replies  •  2020-05-14 18:53:21 +08:00
    asAnotherJack
        1
    asAnotherJack  
       May 12, 2020
    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
       May 12, 2020
    jss
        3
    jss  
    OP
       May 14, 2020
    @asAnotherJack 还是这个表 根据商户 ID 分组,同时统计出 order_type = 1 消费数量和 order_type = 2 提现数量 怎么写?
    asAnotherJack
        4
    asAnotherJack  
       May 14, 2020
    @jss #3 消费数量指什么,次数吗? count(if(order_type = 1,1,null))
    jss
        5
    jss  
    OP
       May 14, 2020
    @asAnotherJack 我没查到这块文档,一直搞不搞懂 sum(if(order_type=1,money,0)) 中 if 里的参数 含义; 那个 0 /null 在什么使用? 因为,我之前进行 count(if(order_type = 1,1,0)) 时,查询结果不正确 ,将 0 改成 null 就对了。
    asAnotherJack
        6
    asAnotherJack  
       May 14, 2020
    @jss #5 搜 count if sum if 网上有很多
    jss
        7
    jss  
    OP
       May 14, 2020 via iPhone
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Privacy   ·   Solana   ·   2362 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 26ms · UTC 01:51 · PVG 09:51 · LAX 18:51 · JFK 21:51
    ♥ Do have faith in what you're doing.