【问题标题】:How to SUM multiple column with multiple conditions and show in one如何对具有多个条件的多列求和并显示在一个中
【发布时间】:2018-07-30 10:36:38
【问题描述】:

我有一个这样的表,现在我需要获取所有数据 GROUP BY tpi

+---------------------+---------+----------------+
| trxDate             | trxType | tpi            |
+---------------------+---------+----------------+
| 2018-06-28 00:00:00 | Sent    | SI0005         |
| 2018-07-02 00:00:00 | Sent    | SI0005         |
| 2018-07-04 00:00:00 | Sent    | SI0005         |
| 2018-05-25 00:00:00 | Open    | SI0007         |
| 2018-06-26 00:00:00 | Open    | SI0007         |
| 2018-05-25 00:00:00 | Sent    | SI0007         |
| 2018-06-23 00:00:00 | Sent    | SI0007         |
+---------------------+---------+----------------+

我需要记录汇总并发送

+---------------------+---------+----------------+
| tpi                 | open    | sent           |
+---------------------+---------+----------------+
|  SI0005             | 0       | 3              |
|  SI0007             | 2       | 2              |   
+---------------------+---------+----------------+

我尝试了一些子查询,但没有得到想要的响应

SELECT  tblcount.tpi, tblcount.qType, count(tblcount.id) total FROM (SELECT id, tpi, 'Open' qType FROM `tbl`WHERE trxType = 'Open' UNION SELECT id, tpi, 'Sent' qType FROM `tbl` WHERE trxType = 'Sent') tblcount GROUP BY  tblcount.third_party_id, tblcount.qType

【问题讨论】:

    标签: javascript mysql sql node.js


    【解决方案1】:

    只使用条件聚合:

    select tpi,
           sum( (trx_type = 'open') ) as num_open,
           sum( (trx_type = 'sent') ) as num_sent
    from tbl
    group by tpi;
    

    这使用 MySQL 扩展,将布尔表达式视为整数上下文中的整数,“1”表示真,“0”表示假。

    【讨论】:

      【解决方案2】:

      你可以做条件聚合:

      select tpi,
             sum(trxType = 'Open') as trxType_open, 
             sum(trxType = 'Sent') as trxType_Sent
      from tbl t
      group by tpi;
      

      【讨论】:

        猜你喜欢
        • 2018-05-04
        • 2013-08-05
        • 2017-09-12
        • 1970-01-01
        • 1970-01-01
        • 2022-12-11
        • 2011-02-14
        • 1970-01-01
        • 2018-09-05
        相关资源
        最近更新 更多